Skip to content

Instantly share code, notes, and snippets.

@osyo-manga
Created October 27, 2015 03:49
Show Gist options
  • Select an option

  • Save osyo-manga/a573d3dfbf77cf786697 to your computer and use it in GitHub Desktop.

Select an option

Save osyo-manga/a573d3dfbf77cf786697 to your computer and use it in GitHub Desktop.
typed
class Module
def sticher_accessor **opt
opt.each { |name, type|
if type.class == Class
# value = type.new
value = nil
else
value = type
type = type.class
end
define_method name do
if instance_variable_defined? "@#{name}"
instance_variable_get "@#{name}"
else
value
end
end
define_method "#{name}=" do |var|
raise "No match type." unless var.class <= type
instance_variable_set "@#{name}", var
end
}
end
end
class X
sticher_accessor name: String, age: Numeric
end
x = X.new.tap{ |x|
p x.name
x.name = "homu"
x.age = 13
# error
# x.name = 13
}
p x
# => #<X:0x00000000f00a78 @name="homu", @age=13>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment