Top Level Namespace

Instance Method Summary collapse

Instance Method Details

#create_dynamic_instance(model_name, args) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/featured_model/steps.rb', line 16

def create_dynamic_instance model_name, args
  attributes = {}
  parsing_state = ""
  args.scan(/(for|with|and) ([^\"]+) "([^\"]*)"/).each do |declaration|
    join_word, key, value = declaration
    parsing_state = join_word unless join_word == 'and'

    case parsing_state
    when 'with' ; attributes[key.gsub(/ /, '_').to_sym] = value
    when 'for'
      associated_model, lookup_attribute = key.split(' with ').map {|x| x.gsub(/ /, '_')}

      # TODO: add an "as ____" clause in order to allow differently named foreign keys.
      fk_name = associated_model

      klass = associated_model.classify.constantize

      attributes[fk_name + '_id'] = klass.first(:conditions => {lookup_attribute => value}).id
    else        ; raise('unknown join word "%s"' % parsing_state)
    end
  end
  send("create_#{model_name}".to_sym, attributes)
end