Metaprogramming and reflection for optional parameters.

In the previous post, the example use reflection via method missing, to emulate some getters and setters.

Another option is to define the setters and getters methods on the fly, refactoring the Mult module using metaprogramming

module Mult

  def create_method(name, &block)
     self.class.send(:define_method, name, &block)
  end

  def initialize(properties = {})
      props.each do |k, v|
  	create_method(k) { @props[k] }
	create_method("#{k}=") { |value| @props[k]=value}
      end

      properties.each do |k, v|
          #k = k.to_s
          raise ArgumentError, "unknown property: #{k}" unless @props.key?(k)
          self.send("#{k}=",v)
      end
  end
end

The iteration over the hash defaults value defines a setter and a getter for each of the properties we define in the book class.

In a second refactoring round, i replace the definitions of the getters/setters with a call to class_eval and defining inside the attribute accessor

module Mult
  def initialize(properties = {})
      props.each do |k, v|
        self.class.class_eval do
           attr_accessor :"#{k}"
        end
	self.send("#{k}=",v)
      end

      properties.each do |k, v|
          k = k.to_s
          raise ArgumentError, "unknown property: #{k}" unless @props.key?(k)
          self.send("#{k}=",v)
      end
  end
end
Advertisements

2 comments so far

  1. […] In a next post i explain ho to  to improve the optinal parameter using meta-programming. […]

  2. Chinmay on

    Small typo:

    props.each do |k, v|
    self.class.class_eval do… should be

    * props.each do |k, v|
    self.class.class_eval do *


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: