Search Results

Search found 62 results on 3 pages for 'metaclass'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • replacing toString using Groovy metaprogramming

    - by Don
    In the following Groovy snippet, I attempt to replace both the hashCode and toString methods String.metaClass.toString = {-> "override" } String.metaClass.hashCode = {-> 22 } But when I test it out, only the replacement of hashCode works String s = "foo" println s.hashCode() // prints 22 println s.toString() // prints "foo" Is toString somehow a special case (possibly for security reasons)?

    Read the article

  • Python class structure ... prep() method?

    - by Adam Nelson
    We have a metaclass, a class, and a child class for an alert system: class AlertMeta(type): """ Metaclass for all alerts Reads attrs and organizes AlertMessageType data """ def __new__(cls, base, name, attrs): new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs) # do stuff to new_class return new_class class BaseAlert(object): """ BaseAlert objects should be instantiated in order to create new AlertItems. Alert objects have classmethods for dequeue (to batch AlertItems) and register (for associated a user to an AlertType and AlertMessageType) If the __init__ function recieves 'dequeue=True' as a kwarg, then all other arguments will be ignored and the Alert will check for messages to send """ __metaclass__ = AlertMeta def __init__(self, **kwargs): dequeue = kwargs.pop('dequeue',None) if kwargs: raise ValueError('Unexpected keyword arguments: %s' % kwargs) if dequeue: self.dequeue() else: # Do Normal init stuff def dequeue(self): """ Pop batched AlertItems """ # Dequeue from a custom queue class CustomAlert(BaseAlert): def __init__(self,**kwargs): # prepare custom init data super(BaseAlert, self).__init__(**kwargs) We would like to be able to make child classes of BaseAlert (CustomAlert) that allow us to run dequeue and to be able to run their own __init__ code. We think there are three ways to do this: Add a prep() method that returns True in the BaseAlert and is called by __init__. Child classes could define their own prep() methods. Make dequeue() a class method - however, alot of what dequeue() does requires non-class methods - so we'd have to make those class methods as well. Create a new class for dealing with the queue. Would this class extend BaseAlert? Is there a standard way of handling this type of situation?

    Read the article

  • Upgrading Redmine, activerecord-mysql2-adapter not recognized

    - by David Kaczynski
    For upgrading Redmine from 1.0.1 to 2.1.2, I need to execute the command: rake db:migrate RAILS_ENV=production However, doing so produces the following error: rake aborted! Please install the mysql2 adapter: gem install activerecord-mysql2-adapter (mysql2 is not part of the bundle. Add it to Gemfile.) I have ran gem install activerecord-mysql2-adapter, but I still get the same error when I try to run the rake ... command. How do I get my RoR app to recognize that I have the mysql2 adapter installed already? or Is there something wrong with my activerecord-mysql2-adapter installation? Results of sudo bundle install: Using rake (10.0.0) Using i18n (0.6.1) Using multi_json (1.3.7) Using activesupport (3.2.8) Using builder (3.0.0) Using activemodel (3.2.8) Using erubis (2.7.0) Using journey (1.0.4) Using rack (1.4.1) Using rack-cache (1.2) Using rack-test (0.6.2) Using hike (1.2.1) Using tilt (1.3.3) Using sprockets (2.1.3) Using actionpack (3.2.8) Using mime-types (1.19) Using polyglot (0.3.3) Using treetop (1.4.12) Using mail (2.4.4) Using actionmailer (3.2.8) Using arel (3.0.2) Using tzinfo (0.3.35) Using activerecord (3.2.8) Using activeresource (3.2.8) Using coderay (1.0.8) Using fastercsv (1.5.5) Using rack-ssl (1.3.2) Using json (1.7.5) Using rdoc (3.12) Using thor (0.16.0) Using railties (3.2.8) Using jquery-rails (2.0.3) Using metaclass (0.0.1) Using mocha (0.12.3) Using mysql (2.8.1) Using net-ldap (0.3.1) Using pg (0.14.1) Using ruby-openid (2.1.8) Using rack-openid (1.3.1) Using bundler (1.2.1) Using rails (3.2.8) Using rmagick (2.13.1) Using shoulda (2.11.3) Using sqlite3 (1.3.6) Using yard (0.8.3) [32mYour bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.[0m Results of sudo find / -name "*mysql2*": /var/lib/gems/1.8/doc/mysql2-0.3.11 /var/lib/gems/1.8/doc/activerecord-3.2.9/ri/ActiveRecord/Base/mysql2_connection-c.ri /var/lib/gems/1.8/doc/activerecord-mysql2-adapter-0.0.3 /var/lib/gems/1.8/doc/activerecord-mysql2-adapter-0.0.3/ri/ActiveRecord/Base/em_mysql2_connection-c.ri /var/lib/gems/1.8/doc/activerecord-mysql2-adapter-0.0.3/ri/ActiveRecord/Base/mysql2_connection-c.ri /var/lib/gems/1.8/gems/mysql2-0.3.11 /var/lib/gems/1.8/gems/mysql2-0.3.11/spec/mysql2 /var/lib/gems/1.8/gems/mysql2-0.3.11/mysql2.gemspec /var/lib/gems/1.8/gems/mysql2-0.3.11/lib/mysql2.rb /var/lib/gems/1.8/gems/mysql2-0.3.11/lib/mysql2 /var/lib/gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.so /var/lib/gems/1.8/gems/mysql2-0.3.11/ext/mysql2 /var/lib/gems/1.8/gems/mysql2-0.3.11/ext/mysql2/mysql2.so /var/lib/gems/1.8/gems/mysql2-0.3.11/ext/mysql2/mysql2_ext.c /var/lib/gems/1.8/gems/mysql2-0.3.11/ext/mysql2/mysql2_ext.h /var/lib/gems/1.8/gems/mysql2-0.3.11/ext/mysql2/mysql2_ext.o /var/lib/gems/1.8/gems/activerecord-3.2.9/lib/active_record/connection_adapters/mysql2_adapter.rb /var/lib/gems/1.8/gems/activerecord-mysql2-adapter-0.0.3 /var/lib/gems/1.8/gems/activerecord-mysql2-adapter-0.0.3/activerecord-mysql2-adapter.gemspec /var/lib/gems/1.8/gems/activerecord-mysql2-adapter-0.0.3/lib/arel/engines/sql/compilers/mysql2_compiler.rb /var/lib/gems/1.8/gems/activerecord-mysql2-adapter-0.0.3/lib/activerecord-mysql2-adapter.rb /var/lib/gems/1.8/gems/activerecord-mysql2-adapter-0.0.3/lib/activerecord-mysql2-adapter /var/lib/gems/1.8/gems/activerecord-mysql2-adapter-0.0.3/lib/active_record/connection_adapters/em_mysql2_adapter.rb /var/lib/gems/1.8/gems/activerecord-mysql2-adapter-0.0.3/lib/active_record/connection_adapters/mysql2_adapter.rb /var/lib/gems/1.8/gems/activerecord-3.2.8/lib/active_record/connection_adapters/mysql2_adapter.rb /var/lib/gems/1.8/cache/mysql2-0.3.11.gem /var/lib/gems/1.8/cache/activerecord-mysql2-adapter-0.0.3.gem /var/lib/gems/1.8/specifications/activerecord-mysql2-adapter-0.0.3.gemspec /var/lib/gems/1.8/specifications/mysql2-0.3.11.gemspec Contents of /usr/share/redmine/Gemfile: source 'http://rubygems.org' gem 'rails', '3.2.8' gem "jquery-rails", "~> 2.0.2" gem "i18n", "~> 0.6.0" gem "coderay", "~> 1.0.6" gem "fastercsv", "~> 1.5.0", :platforms => [:mri_18, :mingw_18, :jruby] gem "builder", "3.0.0" # Optional gem for LDAP authentication group :ldap do gem "net-ldap", "~> 0.3.1" end # Optional gem for OpenID authentication group :openid do gem "ruby-openid", "~> 2.1.4", :require => "openid" gem "rack-openid" end # Optional gem for exporting the gantt to a PNG file, not supported with jruby platforms :mri, :mingw do group :rmagick do # RMagick 2 supports ruby 1.9 # RMagick 1 would be fine for ruby 1.8 but Bundler does not support # different requirements for the same gem on different platforms gem "rmagick", ">= 2.0.0" end end # Database gems platforms :mri, :mingw do group :postgresql do gem "pg", ">= 0.11.0" end group :sqlite do gem "sqlite3" end end platforms :mri_18, :mingw_18 do group :mysql do gem "mysql" end end platforms :mri_19, :mingw_19 do group :mysql do gem "mysql2", "~> 0.3.11" end end platforms :jruby do gem "jruby-openssl" group :mysql do gem "activerecord-jdbcmysql-adapter" end group :postgresql do gem "activerecord-jdbcpostgresql-adapter" end group :sqlite do gem "activerecord-jdbcsqlite3-adapter" end end group :development do gem "rdoc", ">= 2.4.2" gem "yard" end group :test do gem "shoulda", "~> 2.11" # Shoulda does not work nice on Ruby 1.9.3 and seems to need test-unit explicitely. gem "test-unit", :platforms => [:mri_19] gem "mocha", "0.12.3" end local_gemfile = File.join(File.dirname(__FILE__), "Gemfile.local") if File.exists?(local_gemfile) puts "Loading Gemfile.local ..." if $DEBUG # `ruby -d` or `bundle -v` instance_eval File.read(local_gemfile) end # Load plugins' Gemfiles Dir.glob File.expand_path("../plugins/*/Gemfile", __FILE__) do |file| puts "Loading #{file} ..." if $DEBUG # `ruby -d` or `bundle -v` instance_eval File.read(file) end Contents of /usr/share/redmine/Gemfile.lock: GEM remote: http://rubygems.org/ specs: actionmailer (3.2.8) actionpack (= 3.2.8) mail (~> 2.4.4) actionpack (3.2.8) activemodel (= 3.2.8) activesupport (= 3.2.8) builder (~> 3.0.0) erubis (~> 2.7.0) journey (~> 1.0.4) rack (~> 1.4.0) rack-cache (~> 1.2) rack-test (~> 0.6.1) sprockets (~> 2.1.3) activemodel (3.2.8) activesupport (= 3.2.8) builder (~> 3.0.0) activerecord (3.2.8) activemodel (= 3.2.8) activesupport (= 3.2.8) arel (~> 3.0.2) tzinfo (~> 0.3.29) activeresource (3.2.8) activemodel (= 3.2.8) activesupport (= 3.2.8) activesupport (3.2.8) i18n (~> 0.6) multi_json (~> 1.0) arel (3.0.2) builder (3.0.0) coderay (1.0.8) erubis (2.7.0) fastercsv (1.5.5) hike (1.2.1) i18n (0.6.1) journey (1.0.4) jquery-rails (2.0.3) railties (>= 3.1.0, < 5.0) thor (~> 0.14) json (1.7.5) mail (2.4.4) i18n (>= 0.4.0) mime-types (~> 1.16) treetop (~> 1.4.8) metaclass (0.0.1) mime-types (1.19) mocha (0.12.3) metaclass (~> 0.0.1) multi_json (1.3.7) mysql (2.8.1) mysql2 (0.3.11) net-ldap (0.3.1) pg (0.14.1) polyglot (0.3.3) rack (1.4.1) rack-cache (1.2) rack (>= 0.4) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-ssl (1.3.2) rack rack-test (0.6.2) rack (>= 1.0) rails (3.2.8) actionmailer (= 3.2.8) actionpack (= 3.2.8) activerecord (= 3.2.8) activeresource (= 3.2.8) activesupport (= 3.2.8) bundler (~> 1.0) railties (= 3.2.8) railties (3.2.8) actionpack (= 3.2.8) activesupport (= 3.2.8) rack-ssl (~> 1.3.2) rake (>= 0.8.7) rdoc (~> 3.4) thor (>= 0.14.6, < 2.0) rake (10.0.0) rdoc (3.12) json (~> 1.4) rmagick (2.13.1) ruby-openid (2.1.8) shoulda (2.11.3) sprockets (2.1.3) hike (~> 1.2) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) sqlite3 (1.3.6) test-unit (2.5.2) thor (0.16.0) tilt (1.3.3) treetop (1.4.12) polyglot polyglot (>= 0.3.1) tzinfo (0.3.35) yard (0.8.3) PLATFORMS ruby DEPENDENCIES activerecord-jdbcmysql-adapter activerecord-jdbcpostgresql-adapter activerecord-jdbcsqlite3-adapter builder (= 3.0.0) coderay (~> 1.0.6) fastercsv (~> 1.5.0) i18n (~> 0.6.0) jquery-rails (~> 2.0.2) jruby-openssl mocha (= 0.12.3) mysql mysql2 (~> 0.3.11) net-ldap (~> 0.3.1) pg (>= 0.11.0) rack-openid rails (= 3.2.8) rdoc (>= 2.4.2) rmagick (>= 2.0.0) ruby-openid (~> 2.1.4) shoulda (~> 2.11) sqlite3 test-unit yard Results of gem list: actionmailer (3.2.9, 3.2.8) actionpack (3.2.9, 3.2.8) activemodel (3.2.9, 3.2.8) activerecord (3.2.9, 3.2.8) activerecord-mysql2-adapter (0.0.3) activeresource (3.2.9, 3.2.8) activesupport (3.2.9, 3.2.8) arel (3.0.2) builder (3.0.0) bundler (1.2.1) coderay (1.0.8) erubis (2.7.0) fastercsv (1.5.5) hike (1.2.1) i18n (0.6.1) journey (1.0.4) jquery-rails (2.0.3) json (1.7.5) mail (2.4.4) metaclass (0.0.1) mime-types (1.19) mocha (0.12.3) multi_json (1.3.7) mysql (2.8.1) mysql2 (0.3.11) net-ldap (0.3.1) pg (0.14.1) polyglot (0.3.3) rack (1.4.1) rack-cache (1.2) rack-openid (1.3.1) rack-ssl (1.3.2) rack-test (0.6.2) rails (3.2.9, 3.2.8) railties (3.2.9, 3.2.8) rake (10.0.0) rdoc (3.12) rmagick (2.13.1) ruby-openid (2.1.8) shoulda (2.11.3) sprockets (2.2.1, 2.1.3) sqlite3 (1.3.6) thor (0.16.0) tilt (1.3.3) treetop (1.4.12) tzinfo (0.3.35) yard (0.8.3) Results of 'bundle show`: Gems included by the bundle: * actionmailer (3.2.8) * actionpack (3.2.8) * activemodel (3.2.8) * activerecord (3.2.8) * activeresource (3.2.8) * activesupport (3.2.8) * arel (3.0.2) * builder (3.0.0) * bundler (1.2.1) * coderay (1.0.8) * erubis (2.7.0) * fastercsv (1.5.5) * hike (1.2.1) * i18n (0.6.1) * journey (1.0.4) * jquery-rails (2.0.3) * json (1.7.5) * mail (2.4.4) * metaclass (0.0.1) * mime-types (1.19) * mocha (0.12.3) * multi_json (1.3.7) * mysql (2.8.1) * net-ldap (0.3.1) * pg (0.14.1) * polyglot (0.3.3) * rack (1.4.1) * rack-cache (1.2) * rack-openid (1.3.1) * rack-ssl (1.3.2) * rack-test (0.6.2) * rails (3.2.8) * railties (3.2.8) * rake (10.0.0) * rdoc (3.12) * rmagick (2.13.1) * ruby-openid (2.1.8) * shoulda (2.11.3) * sprockets (2.1.3) * sqlite3 (1.3.6) * thor (0.16.0) * tilt (1.3.3) * treetop (1.4.12) * tzinfo (0.3.35) * yard (0.8.3)

    Read the article

  • Simple Observation in Django: How Can I Correctly Modify The `attrs` sent to __new__ of a Django Mod

    - by DGGenuine
    Hello, I'm a strong proponent of the observer pattern, and this is what I'd like to be able to do in my Django models.py: class AModel(Model): __metaclass__ = SomethingMagical @post_save(AnotherModel) @classmethod def observe_another_model_saved(klass, sender, instance, created, **kwargs): pass @pre_init('YetAnotherModel') @classmethod def observe_yet_another_model_initializing(klass, sender, *args, **kwargs): pass @post_delete('DifferentApp.SomeModel') @classmethod def observe_some_model_deleted(klass, sender, **kwargs): pass This would connect a signal with sender = the decorator's argument and receiver = the decorated method. Right now my signal connection code all exists in __init__.py which is okay, but a little unmaintainable. I want this code all in one place, the models.py file. Thanks to helpful feedback from the community I'm very close (I think.) (I'm using a metaclass solution instead of the class decorator solution in the previous question/answer because you can't set attributes on classmethods, which I need.) I am having a strange error I don't understand. At the end of my post are the contents of a models.py that you can pop into a fresh project/application to see the error. Set your database to sqlite and add the application to installed apps. This is the error: Validating models... Unhandled exception in thread started by Traceback (most recent call last): File "/Library/Python/2.6/site-packages//lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 253, in validate raise CommandError("One or more models did not validate:\n%s" % error_text) django.core.management.base.CommandError: One or more models did not validate: local.myothermodel: 'my_model' has a relation with model MyModel, which has either not been installed or is abstract. I've indicated a few different things you can comment in/out to fix the error. First, if you don't modify the attrs sent to the metaclass's __new__, then the error does not arise. (Note even if you copy the dictionary element by element into a new dictionary, it still fails; only using the exact attrs dictionary works.) Second, if you reference the first model by class rather than by string, the error also doesn't arise regardless of what you do in __new__. I appreciate your help. I'll be githubbing the solution if and when it works. Maybe other people would enjoy a simplified way to use Django signals to observe application happenings. #models.py from django.db import models from django.db.models.base import ModelBase from django.db.models import signals import pdb class UnconnectedMethodWrapper(object): sender = None method = None signal = None def __init__(self, signal, sender, method): self.signal = signal self.sender = sender self.method = method def post_save(sender): return _make_decorator(signals.post_save, sender) def _make_decorator(signal, sender): def decorator(view): return UnconnectedMethodWrapper(signal, sender, view) return decorator class ConnectableModel(ModelBase): """ A meta class for any class that will have static or class methods that need to be connected to signals. """ def __new__(cls, name, bases, attrs): unconnecteds = {} ## NO WORK newattrs = {} for name, attr in attrs.iteritems(): if isinstance(attr, UnconnectedMethodWrapper): unconnecteds[name] = attr newattrs[name] = attr.method #replace the UnconnectedMethodWrapper with the method it wrapped. else: newattrs[name] = attr ## NO WORK # newattrs = {} # for name, attr in attrs.iteritems(): # newattrs[name] = attr ## WORKS # newattrs = attrs new = super(ConnectableModel, cls).__new__(cls, name, bases, newattrs) for name, unconnected in unconnecteds.iteritems(): _connect_signal(unconnected.signal, unconnected.sender, getattr(new, name), new._meta.app_label) return new def _connect_signal(signal, sender, receiver, default_app_label): # full implementation also accepts basestring as sender and will look up model accordingly signal.connect(sender=sender, receiver=receiver) class MyModel(models.Model): __metaclass__ = ConnectableModel @post_save('In my application this string matters') @classmethod def observe_it(klass, sender, instance, created, **kwargs): pass @classmethod def normal_class_method(klass): pass class MyOtherModel(models.Model): ## WORKS # my_model = models.ForeignKey(MyModel) ## NO WORK my_model = models.ForeignKey('MyModel')

    Read the article

  • Hotfixing Code running inside Web Container with Groovy

    - by raoulsson
    I have a webapp running that has a bug. I know how to fix it in the sources. However I cannot redeploy the app as I would have to take it offline to do so. (At least not right now). I now want to fix the code "at runtime". Surgery on the living object, so to speak. The app is implemented in Java and is build on top of Seam. I have added a Groovy Console to the app previous to the last release. (A way to run arbitrary code at runtime) The normal way of adding behaviour to a class with Groovy would be similar to this: String.metaClass.foo= { x -> x * x } println "anything".foo(3) This code added the method foo to java.lang.String and prints 9. I can do the same thing with classes running inside my webapp container. New instances will thereafter show the same behaviour: com.my.package.SomeService.metaClass.foo= { x -> x * x } def someService = new com.my.package.SomeService() println someService.foo(3) Works as excpected. All good so far. My problem is now that the container, the web framework, Seam in this case, has already instantiated and cached the classes that I would like to manipulate (that is change their behaviour to reflect my bug fix). Ideally this code would work: com.my.package.SomeService.metaClass.foo= { x -> x * x } def x = org.jboss.seam.Component.getInstance(com.my.package.SomeService) println x.foo(3) However the instantiation of SomeService has already happened and there is no effect. Thus I need a way to make my changes "sticky". Has the groovy magic gone after my script has been run? Well, after logging out and in again, I can run this piece of code and get the expected result: def someService = new com.my.package.SomeService() println someService.foo(3) So the foo method is still around and it looks like my change has been permanent... So I guess the question that remains is how to force Seam to re-instantiate all its components and/or how to permanently make the change on all living instances...?

    Read the article

  • how to show all method and data when the object not has "__iter__" function in python..

    - by zjm1126
    i find a way : (1):the dir(object) is : a="['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate']" (2): b=eval(a) (3)and it became a list of all method : ['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate'] (3)then show the object's method,and all code is : s='' a=eval(str(dir(object))) for i in a: s+=str(i)+':'+str(object[i]) print s but it show error : KeyError: '__class__' so how to make my code running . thanks

    Read the article

  • Python 2.6, 3 abstract base class misunderstanding

    - by Aaron
    I'm not seeing what I expect when I use ABCMeta and abstractmethod. This works fine in python3: from abc import ABCMeta, abstractmethod class Super(metaclass=ABCMeta): @abstractmethod def method(self): pass a = Super() TypeError: Can't instantiate abstract class Super ... And in 2.6: class Super(): __metaclass__ = ABCMeta @abstractmethod def method(self): pass a = Super() TypeError: Can't instantiate abstract class Super ... They both also work fine (I get the expected exception) if I derive Super from object, in addition to ABCMeta. They both "fail" (no exception raised) if I derive Super from list. I want an abstract base class to be a list but abstract, and concrete in sub classes. Am I doing it wrong, or should I not want this in python?

    Read the article

  • Good real-world uses of metaclasses (e.g. in Python)

    - by Carles Barrobés
    I'm learning about metaclasses in Python. I think it is a very powerful technique, and I'm looking for good uses for them. I'd like some feedback of good useful real-world examples of using metaclasses. I'm not looking for example code on how to write a metaclass (there are plenty examples of useless metaclasses out there), but real examples where you have applied the technique and it was really the appropriate solution. The rule is: no theoretical possibilities, but metaclasses at work in a real application. I'll start with the one example I know: Django models, for declarative programming, where the base class Model uses a metaclass to fill the model objects of useful ORM functionality from the attribute definitions. Looking forward to your contributions.

    Read the article

  • Grails unit testing and bootstrap

    - by tbruyelle
    I wrote an unit test for a controller. I have a Bootstrap file which alter the metaclass of domain classes by adding a method asPublicMap(). I use this method in the controller to return domain classes as json but only some selected public fields. My unit test failed because of MissingMethodException for asPublicMap(). As I understood, bootstrap classes are not loaded for unit tests, only for integration tests. That's why I got this error. My question is : Is there another place to put metaclass manipulation in order to take them into account during unit tests ?

    Read the article

  • Django1.1 model field value preprocessing before returning

    - by Satoru.Logic
    Hi, all. I have a model class like this: class Note(models.Model): author = models.ForeignKey(User, related_name='notes') content = NoteContentField(max_length=256) NoteContentField is a custom sub-class of CharField that override the to_python method in purpose of doing some twitter-text-conversion processing. class NoteContentField(models.CharField): __metaclass__ = models.SubfieldBase def to_python(self, value): value = super(NoteContentField, self).to_python(value) from ..utils import linkify return mark_safe(linkify(value)) However, this doesn't work. When I save a Note object like this: note = Note(author=request.use, content=form.cleaned_data['content']) note.save() The conversed value is saved into the database, which is not what I wanna see. What I'm trying to do is to save the raw content into the database, and only make the conversion when the content attribute is later accessed. Would you please tell me what's wrong with this? Thanks to Pierre and Daniel. I have figured out what's wrong. I thought the text-conversion code should be in either to_python or get_db_prep_value, and that's wrong. I should override both of them, make to_python do the conversion and get_db_prep_value return the unconversed value: from ..utils import linkify class NoteContentField(models.CharField): __metaclass__ = models.SubfieldBase def to_python(self, value): self._raw_value = super(NoteContentField, self).to_python(value) return mark_safe(linkify(self._raw_value)) def get_db_prep_value(self, value): return self._raw_value I wonder if there is a better way to implement this?

    Read the article

  • varargs in lambda functions in Python

    - by brain_damage
    Is it possible a lambda function to have variable number of arguments? For example, I want to write a metaclass, which creates a method for every method of some other class and this newly created method returns the opposite value of the original method and has the same number of arguments. And I want to do this with lambda function. How to pass the arguments? Is it possible? class Negate(type): def __new__(mcs, name, bases, _dict): extended_dict = _dict.copy() for (k, v) in _dict.items(): if hasattr(v, '__call__'): extended_dict["not_" + k] = lambda s, *args, **kw: not v(s, *args, **kw) return type.__new__(mcs, name, bases, extended_dict) class P(metaclass=Negate): def __init__(self, a): self.a = a def yes(self): return True def maybe(self, you_can_chose): return you_can_chose But the result is totally wrong: >>>p = P(0) >>>p.yes() True >>>p.not_yes() # should be False Traceback (most recent call last): File "<pyshell#150>", line 1, in <module> p.not_yes() File "C:\Users\Nona\Desktop\p10.py", line 51, in <lambda> extended_dict["not_" + k] = lambda s, *args, **kw: not v(s, *args, **kw) TypeError: __init__() takes exactly 2 positional arguments (1 given) >>>p.maybe(True) True >>>p.not_maybe(True) #should be False True

    Read the article

  • Scope of Groovy's ExpandoMetaClass?

    - by TicketMonster
    Groovy exposes an ExpandoMetaClass that allows you to dynamically add instance and class methods/properties to a POJO. I would like to use it to add an instance method to one of my Java classes: public class Fizz { // ...etc. } Fizz fizz = new Fizz(); fizz.metaClass.doStuff = { String blah -> fizz.buzz(blah) } This would be the equivalent to refactoring the Fizz class to have: public class Fizz { // ctors, getters/setters, etc... public void doStuff(String blah) { buzz(blah); } } My question: Does this add doStuff(String blah) to only this particular instance of Fizz? Or do all instances of Fizz now have a doStuff(String blah) instance method? If the former, how do I get all instances of Fizz to have the doStuff instance method? I know that if I made the Groovy: fizz.metaClass.doStuff << { String blah -> fizz.buzz(blah) } Then that would add a static class method to Fizz, such as Fizz.doStuff(String blah), but that's not what I want. I just want all instances of Fizz to now have an instance method called doStuff. Ideas?

    Read the article

  • Getting output parameter(SYS_REFCURSOR) from Oracle stored procedure in iBATIS 3(by using annotation

    - by yjacket
    I got an example how to call oracle SP in iBATIS 3 without a map file. And now I understand how to call it. But I got another problem that how to get a result from output parameter(Oracle cursor). A part of exception messages is "There is no setter for property named 'rs' in 'class java.lang.Class". Below is my code. Does anyone can help me? Oracle Stored Procedure: CREATE OR REPLACE PROCEDURE getProducts ( rs OUT SYS_REFCURSOR ) IS BEGIN OPEN rs FOR SELECT * FROM Products; END getProducts; Interface: public interface ProductMapper { @Select("call getProducts(#{rs,mode=OUT,jdbcType=CURSOR})") @Options(statementType = StatementType.CALLABLE) List<Product> getProducts(); } DAO: public class ProductDAO { public List<Product> getProducts() { return mapper.getProducts(); // mapper is ProductMapper } } Full Error Message: Exception in thread "main" org.apache.ibatis.exceptions.IbatisException: ### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: Could not set property 'rs' of 'class org.apache.ibatis.reflection.MetaObject$NullObject' with value 'oracle.jdbc.driver.OracleResultSetImpl@1a001ff' Cause: org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'rs' in 'class java.lang.Class' ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### Cause: org.apache.ibatis.reflection.ReflectionException: Could not set property 'rs' of 'class org.apache.ibatis.reflection.MetaObject$NullObject' with value 'oracle.jdbc.driver.OracleResultSetImpl@1a001ff' Cause: org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'rs' in 'class java.lang.Class' at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:8) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:61) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:53) at org.apache.ibatis.binding.MapperMethod.executeForList(MapperMethod.java:82) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:35) at $Proxy8.getList(Unknown Source) at com.dao.ProductDAO.getList(ProductDAO.java:42) at com.Ibatis3Test.main(Ibatis3Test.java:30) Caused by: org.apache.ibatis.reflection.ReflectionException: Could not set property 'rs' of 'class org.apache.ibatis.reflection.MetaObject$NullObject' with value 'oracle.jdbc.driver.OracleResultSetImpl@1a001ff' Cause: org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'rs' in 'class java.lang.Class' at org.apache.ibatis.reflection.wrapper.BeanWrapper.setBeanProperty(BeanWrapper.java:154) at org.apache.ibatis.reflection.wrapper.BeanWrapper.set(BeanWrapper.java:36) at org.apache.ibatis.reflection.MetaObject.setValue(MetaObject.java:120) at org.apache.ibatis.executor.resultset.FastResultSetHandler.handleOutputParameters(FastResultSetHandler.java:69) at org.apache.ibatis.executor.statement.CallableStatementHandler.query(CallableStatementHandler.java:44) at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:55) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:41) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:94) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:72) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:59) ... 7 more Caused by: org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'rs' in 'class java.lang.Class' at org.apache.ibatis.reflection.Reflector.getSetInvoker(Reflector.java:300) at org.apache.ibatis.reflection.MetaClass.getSetInvoker(MetaClass.java:97) at org.apache.ibatis.reflection.wrapper.BeanWrapper.setBeanProperty(BeanWrapper.java:146) ... 16 more

    Read the article

  • How to get a result from output parameter(SYS_REFCURSOR) of Oracle stored procedure in iBATIS 3(by u

    - by yjacket
    I got an example how to call oracle SP in iBATIS 3 without a map file. And now I understand how to call it. But I got another problem that how to get a result from output parameter(Oracle cursor). A part of exception messages is "There is no setter for property named 'rs' in 'class java.lang.Class". Below is my code. Does anyone can help me? Oracle Stored Procedure: CREATE OR REPLACE PROCEDURE getProducts ( rs OUT SYS_REFCURSOR ) IS BEGIN OPEN rs FOR SELECT * FROM Products; END getProducts; Interface: public interface ProductMapper { @Select("call getProducts(#{rs,mode=OUT,jdbcType=CURSOR})") @Options(statementType = StatementType.CALLABLE) List<Product> getProducts(); } DAO: public class ProductDAO { public List<Product> getProducts() { return mapper.getProducts(); // mapper is ProductMapper } } Full Error Message: Exception in thread "main" org.apache.ibatis.exceptions.IbatisException: ### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: Could not set property 'rs' of 'class org.apache.ibatis.reflection.MetaObject$NullObject' with value 'oracle.jdbc.driver.OracleResultSetImpl@1a001ff' Cause: org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'rs' in 'class java.lang.Class' ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### Cause: org.apache.ibatis.reflection.ReflectionException: Could not set property 'rs' of 'class org.apache.ibatis.reflection.MetaObject$NullObject' with value 'oracle.jdbc.driver.OracleResultSetImpl@1a001ff' Cause: org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'rs' in 'class java.lang.Class' at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:8) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:61) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:53) at org.apache.ibatis.binding.MapperMethod.executeForList(MapperMethod.java:82) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:35) at $Proxy8.getList(Unknown Source) at com.dao.ProductDAO.getList(ProductDAO.java:42) at com.Ibatis3Test.main(Ibatis3Test.java:30) Caused by: org.apache.ibatis.reflection.ReflectionException: Could not set property 'rs' of 'class org.apache.ibatis.reflection.MetaObject$NullObject' with value 'oracle.jdbc.driver.OracleResultSetImpl@1a001ff' Cause: org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'rs' in 'class java.lang.Class' at org.apache.ibatis.reflection.wrapper.BeanWrapper.setBeanProperty(BeanWrapper.java:154) at org.apache.ibatis.reflection.wrapper.BeanWrapper.set(BeanWrapper.java:36) at org.apache.ibatis.reflection.MetaObject.setValue(MetaObject.java:120) at org.apache.ibatis.executor.resultset.FastResultSetHandler.handleOutputParameters(FastResultSetHandler.java:69) at org.apache.ibatis.executor.statement.CallableStatementHandler.query(CallableStatementHandler.java:44) at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:55) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:41) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:94) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:72) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:59) ... 7 more Caused by: org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'rs' in 'class java.lang.Class' at org.apache.ibatis.reflection.Reflector.getSetInvoker(Reflector.java:300) at org.apache.ibatis.reflection.MetaClass.getSetInvoker(MetaClass.java:97) at org.apache.ibatis.reflection.wrapper.BeanWrapper.setBeanProperty(BeanWrapper.java:146) ... 16 more

    Read the article

  • Moose::Error::Croak error reporting not from perspective of caller.

    - by crashpoint_zero
    I just recently started out on Moose and its a great OO framework not only to use but also to learn new OO concepts. One of the things I wanted to do was to do error reporting from perspective of caller during object creation. I saw that Moose has the module Moose::Error::Croak which tells Moose to override the default error reporting by croak call. I used it but it did not seem to help Moose code - Foo.pm package Foo; use metaclass ( metaclass => 'Moose::Meta::Class', error_class => 'Moose::Error::Croak', ); use Moose; has 'attr1' => ( is => 'rw', isa => 'Str', required => '1', ); no Moose; 1; Moose code - fooser.pl #!/usr/bin/perl use strict; use warnings; use Foo; my $foobj = Foo->new(); This fails with error: Attribute (attr1) is required at /usr/local/lib/perl/5.8.8/Class/MOP/Class.pm line 364 which is terse than the actual stack trace if Moose::Error::Croak is not used. But it does not report it from perspective of caller. If this were a Perl 5 OO code and I had Foo.pm as: package Foo; use strict; use warnings; use Carp; sub new { my ($class, %args) = @_; my $self = {}; if (! exists $args{'attr1'}) { croak "ERR: did not provide attr1"; } $self->{'attr1'} = $args{attr1}; bless $self, $class; return $self; } 1; And if fooser.pl was executed I would have got the error: "ERR: did not provide attr1 at fooser.pl line 6" which is from the perspective of the caller as it points to line no. 6 of fooser.pl rather than MOP.pm's line no. 364. How can I do this in Moose? Or am I misunderstanding something here?

    Read the article

  • Python: unable to inherit from a C extension.

    - by celil
    I am trying to add a few extra methods to a matrix type from the pysparse library. Apart from that I want the new class to behave exactly like the original, so I chose to implement the changes using inheritance. However, when I try from pysparse import spmatrix class ll_mat(spmatrix.ll_mat): pass this results in the following error TypeError: Error when calling the metaclass bases cannot create 'builtin_function_or_method' instances What is this causing this error? Is there a way to use delegation so that my new class behaves exactly the same way as the original?

    Read the article

  • C++ template meta-programming, number of member variables?

    - by aaa
    hello Is it possible in C++ to determine number of variables/fields in the generic class? for example // suppose I need metaclass number_members determines number of members struct example { int i, j; }; assert(number_members::value==2); I looked through mpl but could not find implementation thanks.

    Read the article

  • why am i getting StackOverflowError?

    - by IttayD
    In groovyConsole I have this: import groovy.util.* import org.codehaus.groovy.runtime.* def gse = new GroovyScriptEngine("c:\\temp") def script = gse.loadScriptByName("say.groovy") this.metaClass.mixin script say("bye") say.groovy contains def say(String msg) { println(msg) }

    Read the article

  • Implementing prototypes OR instantiating class objects

    - by intuited
    I'm wondering how to implement prototypal inheritance in Python. It seems like the way to do this would be to either use a metaclass to cause instantiations to actually be classes, rather than objects, or use some magical powers to transform an existing object into a class. The second method would seem to be more flexible, in that it could be applied to existing objects of varied types, while the first would likely be more convenient for typical use cases. Insights on the practicality of these two approaches, as well as alternative suggestions, are hereby requested.

    Read the article

  • grails metaprogramming

    - by Don
    Hi, My understanding is that there are two obvious places in a Grails app where one can do meta-programming: The init closure of Bootstrap.groovy The doWithDynamicMethods closure of a plugin The meta-programming I'm referring to here should be visible throughout the metaprogramming, typical examples include adding (or replacing) methods of 3rd party classes. String.metaClass.myCustomMethod = { /* implementation omitted */ } The disadvantage of (1), is that the metaprogramming won't be applied when the application is dynamically reloaded. The disadvantage of (2) is that I need to create and maintain an entire plugin just for the sake of a little metaprogramming. Is there a better place to do this kind of metaprogramming? Thanks, Don

    Read the article

  • Django model field value preprocessing before returning

    - by Satoru.Logic
    Hi, all. I have a Note model class like this: class Note(models.Model): author = models.ForeignKey(User, related_name='notes') content = NoteContentField(max_length=256) NoteContentField is a custom sub-class of CharField that override the to_python method in purpose of doing some twitter-text-conversion processing. class NoteContentField(models.CharField): __metaclass__ = models.SubfieldBase def to_python(self, value): value = super(NoteContentField, self).to_python(value) from ..utils import linkify return mark_safe(linkify(value)) However, this doesn't work. When I save a Note object like this: note = Note(author=request.use, content=form.cleaned_data['content']) The conversed value is saved into the database, which is not what I wanna see. Would you please tell me what's wrong with this? Thanks in advance.

    Read the article

  • How do I fix this NameError?

    - by Kyle Kaitan
    I want to use the value v inside of an instance method on the metaclass of a particular object: v = ParserMap[kind][:validation] # We want to use this value later. s = ParserMap[kind][:specs] const_set(name, lambda { p = Parser.new(&s) # This line starts a new scope... class << p define_method :validate do |opts| v.call(self, opts) # => NameError! The `class` keyword above # has started a new scope and we lost # old `v`. end end p }) Unfortunately, the class keyword starts a new scope, so I lose the old scope and I get a NameError. How do I fix this?

    Read the article

  • How to preprocess a Django model field value before return?

    - by Satoru.Logic
    Hi, all. I have a Note model class like this: class Note(models.Model): author = models.ForeignKey(User, related_name='notes') content = NoteContentField(max_length=256) NoteContentField is a custom sub-class of CharField that override the to_python method in purpose of doing some twitter-text-conversion processing. class NoteContentField(models.CharField): __metaclass__ = models.SubfieldBase def to_python(self, value): value = super(NoteContentField, self).to_python(value) from ..utils import linkify return mark_safe(linkify(value)) However, this doesn't work. When I save a Note object like this: note = Note(author=request.use, content=form.cleaned_data['content']) The conversed value is saved into the database, which is not what I wanna see. Would you please tell me what's wrong with this? Thanks in advance.

    Read the article

  • Grails domain class initialization

    - by Don
    Hi, My Grails app has the following Spring bean defined in spring/resources.groovy calendarService(CalendarService) { bean -> bean.initMethod = "init" } This method looks something like: class CalendarService { void init() { User.findByEmail("[email protected]") } } When I call the dynamic finder findByEmail I get a MissingMethodException. My guess is that I'm trying to call this method too early, i.e. before the domain classes have had the dynamic finders added to their metaclass. One solution would be to call CalendarService.init() myself from Bootstrap.init, rather than instructing Spring to call it, but is there a better solution? Thanks, Don

    Read the article

< Previous Page | 1 2 3  | Next Page >