Created
October 27, 2015 03:49
-
-
Save osyo-manga/a573d3dfbf77cf786697 to your computer and use it in GitHub Desktop.
typed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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