Wednesday 15 August 2012

dynamic - Rails - How to define setter/getter dynamically for list of methods inside a class -



dynamic - Rails - How to define setter/getter dynamically for list of methods inside a class -

i have notifications module have classes 1)car 2)bike 3)aeroplane. have serialized column in userfeature model.and have module 'notifications' has list of 11 classes in it.

notifications 1)car 2)bike 3)aeroplane

the hash construction of column notifications in userfeature model must be

{:car => {:mirror => :true, :door => :true} :bike => {:x=> :true, :x => :true} :aeroplane => {:p => :true, :q => :true} }

i can access user_object.notifications access user_object.car , user_object.mirror need write getter/setter methods { defining getter/setter dynamically because dont want write getter/setter every method , unsure number of methods have -> in future may extend }

notifications.constants.each |notification_class| class_methods = "notifications::#{notification_class}".constantize.methods(false) class_methods.each |method| method_name = method[0..-4].split('(')[0] setter_getter_name = "#{notification_class.to_s.underscore}_#{method_name}" define_method("#{setter_getter_name}=") |value| self.notifications = globalutils.form_hash(self.notifications, "#{notification_class}".to_sym, "#{method_name}".to_sym) self[:notifications]["#{notification_class}".to_sym][ "#{method_name}".to_sym] = value end define_method("#{setter_getter_name}") self.notifications.fetch("#{notification_class_name}".to_sym, {}).fetch("#{method_name}".to_sym) end end end

but still when seek access user_object.mirror,

undefined method #<userfeature000043645345>

what doing wrong? need using getter/setter method only

an openstruct info structure, similar hash, allows definition of arbitrary attributes accompanying values. accomplished using ruby’s metaprogramming define methods on class itself.

example:

require 'ostruct' hash = { "country" => "australia", :population => 20_000_000 } info = openstruct.new(hash) p info # -> <openstruct country="australia" population=20000000>

ruby-on-rails dynamic getter-setter

No comments:

Post a Comment