Class: Arstotzka::Options Private

Inherits:
Sinclair::Options
  • Object
show all
Defined in:
lib/arstotzka/options.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Class responsible to hold the options

Options is initialized when using ClassMethods#expose

Examples:

Using options klass and after

class Customer
  attr_reader :name, :age

  def initialize(name:, age:)
    @name = name
    @age  = age
  end

  def adult?
    age >= 18
  end
end

class Store
  include Arstotzka

  expose :customers, klass: Customer, after: :filter_adults

  def initialize(json)
    @json = json
  end

  private

  attr_reader :json

  def filter_adults(values)
    values.select(&:adult?)
  end
end

hash = {
  customers: [{
    name: 'John', age: 21
  }, {
    name: 'Julia', age: 15
  }, {
    name: 'Carol', age: 22
  }, {
    name: 'Bobby', age: 12
  }]
}

instance = Store.new(hash)

instance.customers # returns [
                   #   Customer.new(name: 'John', age: 21),
                   #   Customer.new(name: 'Carol', age: 22)
                   # ]

Using type with klass and after_each

module Arstotzka::TypeCast
  def to_symbolized_hash(value)
    value.symbolize_keys
  end
end

class Drink
  attr_reader :name, :price

  def initialize(name:, price:)
    @name  = name
    @price = price
  end

  def inflate(inflation)
    @price = (price * (1 + inflation)).round(2)
  end
end

class Bar
  include Arstotzka

  expose :drinks, type: :symbolized_hash,
    klass: Drink, after_each: :add_inflation

  def initialize(json)
    @json = json
  end

  private

  attr_reader :json

  def add_inflation(drink)
    drink.inflate(0.1)
    drink
  end
end

json = '{"drinks":[{"name":"tequila","price":7.50},{ "name":"vodka","price":5.50}]}'

hash = JSON.parse(hash)

instance = Bar.new(hash)

instance.drinks # returns [
                #   Drink.new(name: 'tequila', price: 8.25),
                #   Drink.new(name: 'vodka', price: 6.05)
                # ]

Using cached, compact, after and full_path

class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

class Application
  include Arstotzka

  expose :users, full_path: 'users.first_name',
                 compact: true, cached: true,
                 after: :create_person

  def initialize(json)
    @json = json
  end

  private

  attr_reader :json

  def create_person(names)
    names.map do |name|
      warn "Creating person #{name}"
      Person.new(name)
    end
  end
end

# Keys are on camel case (lower camel case)
hash = {
  users: [
    { firstName: 'Lucy',  email: '[email protected]' },
    { firstName: 'Bobby', email: '[email protected]' },
    { email: '[email protected]' },
    { firstName: 'Arthur', email: '[email protected]' }
  ]
}

instance = Application.new(hash)

instance.users # trigers the warn "Creating person <name>" 3 times
               # returns [
               #   Person.new('Lucy'),
               #   Person.new('Bobby'),
               #   Person.new('Arthur')
               # ]
instance.users # returns the same value, without triggering warn

Working with snake case hash

class JobSeeker
  include Arstotzka

  expose :applicants, case: :snake, default: 'John Doe',
                      full_path: 'applicants.full_name',
                      compact: true, json: :@hash

  def initialize(hash)
    @hash = hash
  end
end

hash = {
  'applicants' => [
    {
      'full_name' => 'Robert Hatz',
      'email' => '[email protected]'
    }, {
      'full_name' => 'Marina Wantz',
      'email' => '[email protected]'
    }, {
      'email' => '[email protected]'
    }
  ]
}

instance = JobSeeker.new(hash)

instance.applicants # returns [
                    #   'Robert Hatz',
                    #   'Marina Wantz',
                    #   'John Doe'
                    # ]

Deep path with flatten option

class ShoppingMall
  include Arstotzka

  expose :customers, path: 'floors.stores',
                     flatten: true, json: :hash

  def initialize(hash)
    @hash = hash
  end

  private

  attr_reader :hash
end

hash = {
  floors: [{
    name: 'ground', stores: [{
      name: 'Starbucks', customers: %w[
        John Bobby Maria
      ]
    }, {
      name: 'Pizza Hut', customers: %w[
        Danny LJ
      ]
    }]
  }, {
    name: 'first', stores: [{
      name: 'Disney', customers: %w[
        Robert Richard
      ]
    }, {
      name: 'Comix', customers: %w[
        Linda Ariel
      ]
    }]
  }]
}

instance = ShoppingMall.new(hash)

instance.customers # returns %w[
                   #   John Bobby Maria
                   #   Danny LJ Robert Richard
                   #   Linda Ariel
                   # ]

Instance Method Summary collapse

Constructor Details

#initialize(options_hash) ⇒ Arstotzka::Options

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates a new instance of Options

Parameters:

  • options_hash (Hash)

    options hash Options hash are initialized when using ClassMethods#expose

Options Hash (options_hash):

  • instance (Object)

    instance whose method was called

  • key (Symbol, String)

    name of method called. This will be used as instance variable when caching results

  • after (String, Symbol)

    instance method to be called on the returning value returned by Crawler before being returned by Fetcher. The result of the method call will be the actual value (used by PostProcessor)

  • after_each (String, Symbol)

    instance method to be called on each element found when crawling the hash. If an array should be returned, after_each will be called on each individual elements (even nil elements) while after is only called on the collection. (used by Wrapper)

  • cached (Boolean, Symbol)

    Flag to ensure there value is cached after first fetching. (used by Fetcher::Cache)

    • false/nil : no cache, fetcher will always look in the hash for the value

    • true : Simple cache, nil values are always considered not cached

    • :full : cache even nil values

  • case (Symbol)

    case type of the keys in the hash (used by KeyChanger)

    • :snake : snake_cased keys

    • :lower_camel : lowerCamelCased keys

    • :upper_camel : UperCamelCased keys

  • compact (Boolean)

    flag signallying if nil values should be removed of array (applying Array#compact) (used by Crawler)

  • default (Object)

    default value to be returned when failing to fetch a value (used by Crawler)

  • flatten (Boolean)

    flag signallying if multi levels arrays should be flattened to one level array (applying Array#flatten) (used by PostProcessor)

  • full_path (String)

    full path of keys to be used in when not wanting to have the attribute defined as key. (eg. ‘person.name’) (used by Crawler)

  • klass (Class)

    class to wrap the value (used by Wrapper)

  • json (String, Symbol)

    name of the method or variable used to fetch the hash to be crawled (eg. :hash, :@hash, “@@config”) (used by HashReader)

  • path (String, Symbol)

    base path to be crawled. (used by Crawler)

  • type (String, Symbol)

    type to cast the value. The possible type_cast is defined by TypeCast (used by Wrapper)

    • integer

    • string

    • float

See Also:



265
266
267
268
269
270
271
# File 'lib/arstotzka/options.rb', line 265

def initialize(options_hash)
  klass = options_hash.delete(:class)
  warn ":class has been deprecated, prefer 'expose klass: #{klass}'" if klass
  options_hash[:klass] ||= klass

  super(options_hash)
end

Instance Method Details

#==(other) ⇒ TrueClass, FalseClass

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Checks if another instance equals self

Parameters:

  • other (Object)

Returns:

  • (TrueClass, FalseClass)


297
298
299
300
301
# File 'lib/arstotzka/options.rb', line 297

def ==(other)
  return false unless other.class == self.class

  to_h == other.to_h
end

#keysArray<String>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Retuns all keys used when fetching

Returns:

  • (Array<String>)


285
286
287
288
289
290
# File 'lib/arstotzka/options.rb', line 285

def keys
  return full_path.split('.') if full_path
  return [key.to_s] unless path&.present?

  [path, key].compact.join('.').split('.')
end