ruby - Dynamically including a Rails Concern -
my objective dynamically load set of methods activerecord model instance based on attribute that's set:
class book < activerecord::base after_initialize |cp| self.class.include "#{cp.subject}".constantize end end
i have following concerns:
module ruby extend activesupport::concern def get_framework 'rails' end end module python extend activesupport::concern def get_framework 'django' end end
then, when run these separately, correct framework string:
python_book = book.create(:subject => 'python', :id => 1) python_book.get_framework -> 'django' ruby_book = book.create(:subject => 'ruby', :id => 2) ruby_book.get_framework -> 'rails'
my problem when have both of books returned in query, concern included last in result set , not picking correct concern methods.
books.all.order(:id => 'asc').collect |book| puts book.get_framework end # result ['rails', 'rails']
i assuming because 'include' happening @ class level , not instance level. love how clean , make work.
use .extend
add instance methods instances of book
instead.
extends in action:
module greeter def say_hello "hello" end end
irb(main):008:0> = object.new => #<object:0x00000101e01c38> irb(main):009:0> a.extend(greeter) => #<object:0x00000101e01c38> irb(main):010:0> a.say_hello => "hello" irb(main):011:0> object.new.say_hello nomethoderror: undefined method `say_hello' #<object:0x00000101e196d0>
class book < activerecord::base after_initialize |cp| self.extend subject.constantize end end
Comments
Post a Comment