class Dystruct
Constants
- VERSION
Attributes
attrs[R]
to_h[R]
to_hash[R]
Public Class Methods
inherited(subclass)
click to toggle source
# File lib/dystruct.rb, line 10 def self.inherited(subclass) subclass.extend ClassMethods subclass.include InstanceMethods end
new(hash = {})
click to toggle source
# File lib/dystruct.rb, line 19 def initialize(hash = {}) unless hash.class <= Hash fail WrongArgument, "[Dystruct ERROR]: `#{self.class}` expects to receive a `Hash` or and object having `Hash` as ancestor." end @attrs = hash @attrs.each do |k, v| define_dystruct_method(k, v) end end
Public Instance Methods
[](key)
click to toggle source
# File lib/dystruct.rb, line 29 def [](key) attrs[key] end
[]=(key, value)
click to toggle source
# File lib/dystruct.rb, line 33 def []=(key, value) set_attribute(key, value) end
method_missing(name, *args, &block)
click to toggle source
Calls superclass method
Dystruct::InstanceMethods#method_missing
# File lib/dystruct.rb, line 37 def method_missing(name, *args, &block) if name =~ /\A\w+=\z/ set_attribute_macro(name, *args, &block) elsif out = provided_macro(name) out[:out] else super end end
Private Instance Methods
define_dystruct_method(key, value)
click to toggle source
# File lib/dystruct.rb, line 67 def define_dystruct_method(key, value) define_singleton_method(key) { attrs.fetch(key) } define_singleton_method("#{key}_provided?") { true } define_singleton_method("#{key}_not_provided?") { false } end
provided_macro(name)
click to toggle source
# File lib/dystruct.rb, line 55 def provided_macro(name) case name.to_s when /\A\w+_not_provided\?\z/ then { out: true } when /\A\w+_provided\?\z/ then { out: false } end end
set_attribute(key, value)
click to toggle source
# File lib/dystruct.rb, line 62 def set_attribute(key, value) attrs[key] = value define_dystruct_method(key, value) end
set_attribute_macro(name, *args, &block)
click to toggle source
# File lib/dystruct.rb, line 49 def set_attribute_macro(name, *args, &block) value = args.first || block key = name.to_s.gsub('=', '').to_sym set_attribute(key, value) end