Sha256: 37c7556660679da94db2a5c2475c498b60bbbc23157411f35dfa127ca1dfe1c2

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true
module GetYourRep
  # Base class for external responses
  class Base
    # Accepts an options hash and creates setter and getter attribute methods from the hash keys.
    # After initializing methods the values are added to the attributes.
    # Taken with gratitude from davidbella https://gist.github.com/davidbella/6918455
    def initialize(options = {})
      options.each do |attr, value|
        # Recent responses from OpenStates have had '+' appended to some keys.
        # Trim that off or it throws an error.
        attr = attr.delete('+')
        create_setters_from_opts(attr)
        create_getters_from_opts(attr)
        add_value_to_attr(attr, value)
      end
    end

    private

    def add_value_to_attr(attr, value)
      send("#{attr}=".to_sym, value)
    end

    def create_getters_from_opts(attr)
      self.class.send(:define_method, attr.to_sym) do
        instance_variable_get('@' + attr.to_s)
      end
    end

    def create_setters_from_opts(attr)
      self.class.send(:define_method, "#{attr}=".to_sym) do |val|
        instance_variable_set('@' + attr.to_s, val)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
get_your_rep-1.2.0 lib/get_your_rep/responses/base.rb
get_your_rep-1.1.1 lib/get_your_rep/responses/base.rb