Module: TaggedUnion
- Defined in:
- lib/emery/taggedunion.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
Class Method Details
.included(base) ⇒ Object
52 53 54 55 56 |
# File 'lib/emery/taggedunion.rb', line 52 def self.included(base) base.extend ClassMethods attr_accessor :current_tag attr_accessor :current_value end |
Instance Method Details
#==(other) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/emery/taggedunion.rb', line 15 def ==(other) begin T.check(self.class, other) self.class..keys.each do |attr| if self.instance_variable_get("@#{attr}") != other.instance_variable_get("@#{attr}") return false end end return true rescue return false end end |
#copy(params) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/emery/taggedunion.rb', line 29 def copy(params) params.keys.each do |attr| if !self.class..key?(attr) raise TypeError.new("Non existing attribute #{attr}") end end new_params = self.class..keys.map do |attr| attr_value = if params.key?(attr) params[attr] else self.instance_variable_get("@#{attr}") end [attr, attr_value] end.to_h return self.class.new(new_params) end |
#initialize(params) ⇒ Object
2 3 4 5 6 7 8 9 10 11 12 13 |
# File 'lib/emery/taggedunion.rb', line 2 def initialize(params) if params.length != 1 raise ArgumentError.new("Tagged union #{self.class} should have one only one tag set, found #{params.length}" ) end tag = params.keys[0] tag_type = self.class.[tag] tag_value = T.check_var(tag, tag_type, params[tag]) self.instance_variable_set("@#{tag}", tag_value) self.current_tag = tag self.current_value = tag_value end |