Sha256: 011e3d5c3a284aa1fcda8e25afe5882921a199e72e40e3fbcdbb66a5e200b07e

Contents?: true

Size: 1.94 KB

Versions: 4

Compression:

Stored size: 1.94 KB

Contents

require 'enrichment_db/error'
require 'enrichment_db/version'
require 'enrichment_db/helper'

module EnrichmentDb
  module_function

  class DatumModel
    attr_accessor :attrs
    alias :to_hash :attrs

    # Define methods that retrieve the value from an initialized instance variable Hash, using the attribute as a key
    #
    # @overload self.lazy_attr_reader(attr)
    #   @param attr [Symbol]
    # @overload self.lazy_attr_reader(attrs)
    #   @param attrs [Array<Symbol>]
    def self.lazy_attr_reader(*attrs)
      attrs.each do |attribute|
        class_eval do
          define_method attribute do
            @attrs[attribute.to_s] || @attrs[attribute.to_sym]
          end
        end
      end
    end

    def self.by_id(table_name, id)
      schema_name = self::DATABASE_NAME
      uid_name = self::UID_NAME
      puts "Finding object from #{table_name} with #{uid_name} = '#{id}'."
      query = "SELECT * FROM #{schema_name}.#{table_name} where #{uid_name} = $1"
      values = [id]
      
      result = EnrichmentDb.request(schema_name, query, values).collect do |record|
        record
      end

      format_result(result)
    end

    def self.all(table_name, schema_name = nil)
      schema_name = schema_name || self::DATABASE_NAME
      puts "Finding all objects from #{table_name}"
      query = "SELECT * FROM #{schema_name}.#{table_name}"
      
      result = EnrichmentDb.request(schema_name, query).collect do |record|
        record
      end

      format_result(result)
    end

    def self.format_result(result)
      if result.size > 0 
        puts "Found #{result.size} object/s"
        result
      else
        puts "Nothing found"
      end
    end

    # Initializes a new Base object
    #
    # @param attrs [Hash]
    # @return [DatumModel]
    def initialize(attrs={})
      @attrs = attrs.dup
    end
  end
end

require 'enrichment_db/geo'
require 'enrichment_db/language'
require 'enrichment_db/census'
require 'datum'
require 'db'

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
enrichment_db-0.1.9 lib/enrichment_db.rb
enrichment_db-0.1.8 lib/enrichment_db.rb
enrichment_db-0.1.7 lib/enrichment_db.rb
enrichment_db-0.1.6 lib/enrichment_db.rb