Class: RequestBag

Inherits:
Object
  • Object
show all
Defined in:
lib/primate/request_bag.rb

Instance Method Summary collapse

Constructor Details

#initialize(data, helpers) ⇒ RequestBag

initialize with JavaScript object data

Parameters:

  • data (Object)

    JavaScript object from runtime



9
10
11
# File 'lib/primate/request_bag.rb', line 9

def initialize(data, helpers)
  @data = type(data, helpers)
end

Instance Method Details

#[](key) ⇒ Object

Get a value by key (alias for get, Ruby style)



24
25
26
# File 'lib/primate/request_bag.rb', line 24

def [](key)
  get(key)
end

#get(key) ⇒ String

get a value by key

Parameters:

  • key (String)

    The key to look up

Returns:

  • (String)

    The value as string



18
19
20
21
# File 'lib/primate/request_bag.rb', line 18

def get(key)
  raise "RequestBag has no key #{key}" unless has?(key)
  @data[key].to_s
end

#has?(key) ⇒ Boolean

Whether the bag contains a defined value for the key

Parameters:

  • key (String)

    The key to check

Returns:

  • (Boolean)

    True if key exists with defined value



40
41
42
# File 'lib/primate/request_bag.rb', line 40

def has?(key)
  @data.key?(key) && !@data[key].nil?
end

#parse(schema, coerce = false) ⇒ Object

Parse the entire bag with a schema

Parameters:

  • schema (Object)

    Object with parse method

  • coerce (Boolean) (defaults to: false)

    Whether to coerce types

Returns:

  • (Object)

    Parsed result



49
50
51
# File 'lib/primate/request_bag.rb', line 49

def parse(schema, coerce = false)
  schema.parse(@data, coerce)
end

#sizeInteger

Size of the bag

Returns:

  • (Integer)

    Number of entries



63
64
65
# File 'lib/primate/request_bag.rb', line 63

def size
  @data.size
end

#to_hHash

Convert to hash (Ruby standard conversion)

Returns:

  • (Hash)

    The underlying data



56
57
58
# File 'lib/primate/request_bag.rb', line 56

def to_h
  @data
end

#try(key) ⇒ String?

Try to get a value by key

Parameters:

  • key (String)

    The key to look up

Returns:

  • (String, nil)

    The value or nil if absent



32
33
34
# File 'lib/primate/request_bag.rb', line 32

def try(key)
  has?(key) ? @data[key].to_s : nil
end