Module: Quant::Attributes::InstanceMethods

Defined in:
lib/quant/attributes.rb

Instance Method Summary collapse

Instance Method Details

#each_attribute(&block) ⇒ Object

Iterates over all defined attributes in a child => parent hierarchy, and yields the name and entry for each.



57
58
59
60
61
62
63
64
65
66
# File 'lib/quant/attributes.rb', line 57

def each_attribute(&block)
  klass = self.class
  loop do
    attributes = Attributes.registry[klass]
    break if attributes.nil?

    attributes.each{ |name, entry| block.call(name, entry) }
    klass = klass.superclass
  end
end

#initializeObject



50
51
52
53
# File 'lib/quant/attributes.rb', line 50

def initialize(...)
  initialize_attributes
  super(...)
end

#initialize_attributesObject

Initializes the defined attributes with default values and defines accessor methods for each attribute. If a child class redefines a parent’s attribute, the child’s definition will be used.



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/quant/attributes.rb', line 72

def initialize_attributes
  each_attribute do |name, entry|
    # use the child's definition, skipping the parent's
    next if respond_to?(name)

    ivar_name = "@#{name}"
    instance_variable_set(ivar_name, entry[:default])
    define_singleton_method(name) { instance_variable_get(ivar_name) }
    define_singleton_method("#{name}=") { |value| instance_variable_set(ivar_name, value) }
  end
end

#to_hHash

Serializes keys that have been defined as serializeable attributes Key values that are nil are removed from the hash

Returns:

  • (Hash)

    The serialized attributes as a Ruby Hash.



87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/quant/attributes.rb', line 87

def to_h
  {}.tap do |key_values|
    each_attribute do |name, entry|
      next unless entry[:key]

      ivar_name = "@#{name}"
      value = instance_variable_get(ivar_name)

      key_values[entry[:key]] = value if value
    end
  end
end

#to_json(*args) ⇒ String

Serializes keys that have been defined as serializeable attributes Key values that are nil are removed from the hash

Returns:

  • (String)

    The serialized attributes as a JSON string.



103
104
105
# File 'lib/quant/attributes.rb', line 103

def to_json(*args)
  Oj.dump(to_h, *args)
end