Sha256: 7c0b741ad1d454d05279f535058e42b78fecda04b2bf1b4298113e1826d23759

Contents?: true

Size: 1.33 KB

Versions: 2

Compression:

Stored size: 1.33 KB

Contents

require 'ostruct'

module BqFactory
  class Record
    include Enumerable

    delegate :include?, to: :items

    def initialize(schema, params = {})
      raise ArgumentError.new, "Schema is not Array" unless schema.is_a? Array

      schema.each do |hash|
        column = OpenStruct.new(hash)
        items[column.name] = Attribute.new(column.name, column.type)
      end

      params.each { |key, value| send(:"#{key}=", value) }
    end

    def find(name)
      if include?(name)
        items[name].value
      else
        raise ArgumentError.new, "#{name} is not attribute"
      end
    end
    alias :[] :find

    def each(&block)
      items.values.uniq.each(&block)
    end

    def method_missing(method_name, *args, &block)
      name = trim_equal(method_name)
      return super unless respond_to?(name)
      return items[name].value = args.first if include_equal?(method_name)
      items[name].value
    end

    def respond_to?(method_name)
      include? trim_equal(method_name) || super
    end

    def to_sql
      "SELECT #{items.values.map(&:to_sql).join(', ')}"
    end

    private

    def include_equal?(value)
      !!value.to_s.match(/(?<name>.*)=\Z/)
    end

    def trim_equal(value)
      md = value.to_s.match(/(?<name>.*)=\Z/)
      md ? md[:name] : value.to_s
    end

    def items
      @items ||= {}
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bq_factory-0.2.0 lib/bq_factory/record.rb
bq_factory-0.1.1 lib/bq_factory/record.rb