Skip to content

Instantly share code, notes, and snippets.

@jtomschroeder
Created August 9, 2013 16:59
Show Gist options
  • Save jtomschroeder/6195229 to your computer and use it in GitHub Desktop.
Save jtomschroeder/6195229 to your computer and use it in GitHub Desktop.
custom attrs
module Attrs
def attr_initialize(*vars)
define_method(:initialize) do |*values|
unless values.length == vars.length
raise ArgumentError, "wrong number of arguments (#{values.length} for #{vars.length})"
end
vars.zip(values).each do |var, value|
instance_variable_set("@#{var}", value)
end
end
end
def attr_prop_initialize(*vars)
attr_initialize *vars
attr_accessor *vars
end
end
class Class
include Attrs
end
require_relative "attrs"
class Test
attr_prop_initialize :t1, :t2
def add
@t1 + @t2
end
end
t = Test.new(1, 2)
puts t.t1
puts t.add
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment