Skip to content

Instantly share code, notes, and snippets.

@zdennis
Created July 4, 2012 15:16
Show Gist options
  • Save zdennis/3047852 to your computer and use it in GitHub Desktop.
Save zdennis/3047852 to your computer and use it in GitHub Desktop.
coffee-script style constructor for ruby (for automatic instance variable setting)
class Class
def initialize(*vars)
keys = vars.map{ |k| k.to_s.sub(/^@/, '')}
define_method :initialize do |args|
args.each_pair do |k,v|
raise ArgumentError, "Unexpected argument #{k}" unless keys.include?(k.to_s)
instance_variable_set "@#{k}", v
end
end
end
end
class Tile
initialize :@location, :@area
end
Tile.new location: "1,3", area: "24sqft."
@mvanholstyn
Copy link

What about default values, and a block to allow you to write additional code in the initialize method?

class Tile
  initialize :@location, :@area, @:color => "white" do
    # other things to do initialize
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment