Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning constructor arguments into instance variables [duplicate]

Tags:

ruby

Possible Duplicate:
Idiomatic object creation in ruby

There are many occaisions when I have an initialize method that looks like this:

class Foo  
    def initialize bar, buz, ...
        @bar, @buz, ... = bar, buz, ...
    end
end

Is there a way to do this with a simple command like:

class Foo
    attr_constructor :bar, :buz, ...
end

where the symbols represent the name of the instance variables (with the spirit/flavor of attr_accessor, attr_reader, attr_writer)?


I was wondering if there is a built in way or a more elegant way of doing something like this:

class Class
    def attr_constructor *vars
        define_method("initialize") do |*vals|
            vars.zip(vals){|var, val| instance_variable_set("@#{var}", val)}
        end
    end
end

so that I can use it like this:

class Foo
    attr_constructor :foo, :bar, :buz
end

p Foo.new('a', 'b', 'c')      # => #<Foo:0x93f3e4c @foo="a", @bar="b", @buz="c">
p Foo.new('a', 'b', 'c', 'd') # => #<Foo:0x93f3e4d @foo="a", @bar="b", @buz="c">
p Foo.new('a', 'b')           # => #<Foo:0x93f3e4e @foo="a", @bar="b", @buz=nil>
like image 836
sawa Avatar asked Oct 21 '11 02:10

sawa


3 Answers

I'd use OpenStruct:

require 'ostruct'

class Foo < OpenStruct
end

f = Foo.new(:bar => "baz")
f.bar
#=> "baz"

Edit: Ah OK, sorry misunderstood you. How about just:

class Foo   
  def initialize(*args)
    @baz, @buz = args
  end
end
like image 116
Alex Peattie Avatar answered Oct 03 '22 00:10

Alex Peattie


Would this work for you?

class Foo  
    def initialize(hash)
        hash.each { |k,v| instance_variable_set("@#{k}", v) }
    end
end
like image 26
Moiz Raja Avatar answered Oct 03 '22 00:10

Moiz Raja


Interesting question. A little meta-programming should take care of it.

module Attrs
  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      class << self
        attr_accessor :attrs
      end
    end
  end

  module ClassMethods
    # Define the attributes that each instance of the class should have
    def has_attrs(*attrs)
      self.attrs = attrs
      attr_accessor *attrs
    end
  end

  def initialize(*args)
    raise ArgumentError, "You passed too many arguments!" if args.size > self.class.attrs.size
    # Loop through each arg, assigning it to the appropriate attribute (based on the order)
    args.each_with_index do |val, i|
      attr = self.class.attrs[i]
      instance_variable_set "@#{attr}", val
    end
  end
end

class Foo
  include Attrs
  has_attrs :bar, :buz
end

f = Foo.new('One', 'Two')
puts f.bar
puts f.buz

Of course the downside to this is inflexibility - you have to pass your constructor arguments in a specific order. Of course that's how most programming languages are. Rails people might argue you should instead do

f = Foo.new(:bar => 'One', :baz => 'Two')

which would allow you to pass in attrs in any order, as well as strip away most of the meta-programming. But that is a lot more to type.

like image 26
bioneuralnet Avatar answered Oct 02 '22 22:10

bioneuralnet