Class: Pickle::Parser

Inherits:
Object
  • Object
show all
Includes:
Matchers
Defined in:
lib/pickle/parser.rb,
lib/pickle/parser/matchers.rb

Defined Under Namespace

Modules: Matchers

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Methods included from Matchers

#capture_key_and_value_in_field, #capture_name_in_label, #capture_number_in_ordinal, #match_factory, #match_field, #match_fields, #match_index, #match_indexed_model, #match_label, #match_labeled_model, #match_mapping, #match_model, #match_ordinal, #match_plural_factory, #match_predicate, #match_prefix, #match_quoted, #match_value

Constructor Details

- (Parser) initialize(options = {})



9
10
11
# File 'lib/pickle/parser.rb', line 9

def initialize(options = {})
  @config = options[:config] || raise(ArgumentError, "Parser.new requires a :config")
end

Instance Attribute Details

- (Object) config (readonly)

Returns the value of attribute config



7
8
9
# File 'lib/pickle/parser.rb', line 7

def config
  @config
end

Instance Method Details

- (Object) canonical(str)

returns really underscored name



36
37
38
# File 'lib/pickle/parser.rb', line 36

def canonical(str)
  str.to_s.underscore.gsub(' ','_').gsub('/','_')
end

- (Object) parse_field(field)

given a string like 'foo: expr' returns => value



27
28
29
30
31
32
33
# File 'lib/pickle/parser.rb', line 27

def parse_field(field)
  if field =~ /^#{capture_key_and_value_in_field}$/
    { $1 => eval($2) }
  else
    raise ArgumentError, "The field argument is not in the correct format.\n\n'#{field}' did not match: #{match_field}"
  end
end

- (Object) parse_fields(fields)

given a string like 'foo: “bar”, bar: “baz”' returns => “bar”, “bar” => “baz”



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/pickle/parser.rb', line 14

def parse_fields(fields)
  if fields.blank?
    {}
  elsif fields =~ /^#{match_fields}$/
    fields.scan(/(#{match_field})(?:,|$)/).inject({}) do |m, match|
      m.merge(parse_field(match[0]))
    end
  else
    raise ArgumentError, "The fields string is not in the correct format.\n\n'#{fields}' did not match: #{match_fields}" 
  end
end

- (Object) parse_index(index)



50
51
52
53
54
55
56
# File 'lib/pickle/parser.rb', line 50

def parse_index(index)
  case index
  when nil, '', 'last' then -1
  when /#{capture_number_in_ordinal}/ then $1.to_i - 1
  when 'first' then 0
  end
end

- (Object) parse_model(model_name)

return [factory_name, name or integer index]



41
42
43
44
45
46
47
48
# File 'lib/pickle/parser.rb', line 41

def parse_model(model_name)
  apply_mappings!(model_name)
  if /#{capture_index} #{capture_factory}$/ =~ model_name
    [canonical($2), parse_index($1)]
  elsif /#{capture_factory}#{capture_name_in_label}?$/ =~ model_name
    [canonical($1), canonical($2)]
  end
end