Ruby Metaprogramming: Dynamically defining method based on child instance attribute -


i'm creating presenter base class supposed wrap activerecord object.

class basepresenter   def initialize object     @object = object   end    def method_missing(*args, &block)     @object.send(*args, &block)   end    def self.wrap collection     collection.map { |item| new item }   end end 

for each child class, able dynamically define method based on child attribute @ initialization, listpresenter like:

class listpresenter < basepresenter end 

should respond list_id wrapped list object's id.

how short of defining on every child class? i've tried following in def initialize(object), both of not work. prefer avoid eval based approaches if possible hear it's code smell.

class approach (adds method basepresenter, not child classes)

self.class.send(:define_method, "#{object.class.name.underscore}_id")   @object.id end 

metaclass approach (unable access instance variables object or @object):

class << self   define_method "#{@object.class.name.underscore}_id"     @object.id   end end 

use class#inherited hook dynamically add method whenever sub-class inherits basepresenter.

class basepresenter   def self.inherited(sub_klass)     sub_klass.send(:define_method, "#{sub_klass.name.underscore.split("_")[0...-1].join("_")}_id")       instance_variable_get("@object").id     end   end end   class listpresenter < basepresenter end  # sending rails model object below l = listpresenter.new(user.first) l.list_id #=> 1 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -