mrflip-pickle 0.1.13

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,48 @@
1
+ require 'ostruct'
2
+
3
+ module Pickle
4
+ class Config
5
+ attr_writer :adapters, :factories, :mappings, :predicates
6
+
7
+ def initialize(&block)
8
+ configure(&block) if block_given?
9
+ end
10
+
11
+ def configure(&block)
12
+ yield(self)
13
+ end
14
+
15
+ def adapters
16
+ @adapters ||= [:machinist, :factory_girl, :active_record]
17
+ end
18
+
19
+ def adapter_classes
20
+ adapters.map {|a| a.is_a?(Class) ? a : "pickle/adapter/#{a}".classify.constantize}
21
+ end
22
+
23
+ def factories
24
+ @factories ||= adapter_classes.reverse.inject({}) do |factories, adapter|
25
+ factories.merge(adapter.factories.inject({}){|h, f| h.merge(f.name => f)})
26
+ end
27
+ end
28
+
29
+ def predicates
30
+ @predicates ||= Pickle::Adapter.model_classes.map do |k|
31
+ k.public_instance_methods.select{|m| m =~ /\?$/} + k.column_names
32
+ end.flatten.uniq
33
+ end
34
+
35
+ def mappings
36
+ @mappings ||= []
37
+ end
38
+
39
+ # Usage: map 'me', 'myself', 'I', :to => 'user: "me"'
40
+ def map(*args)
41
+ options = args.extract_options!
42
+ raise ArgumentError, "Usage: map 'search' [, 'search2', ...] :to => 'replace'" unless args.any? && options[:to].is_a?(String)
43
+ args.each do |search|
44
+ self.mappings << OpenStruct.new(:search => search, :replace => options[:to])
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,36 @@
1
+ module Pickle
2
+ module Email
3
+ # return the deliveries array, optionally selected by the passed fields
4
+ def emails(fields = nil)
5
+ @emails = ActionMailer::Base.deliveries.select {|m| email_has_fields?(m, fields)}
6
+ end
7
+
8
+ def email(ref, fields = nil)
9
+ (match = ref.match(/^#{capture_index_in_email}$/)) or raise ArgumentError, "argument should match #{match_email}"
10
+ @emails or raise RuntimeError, "Call #emails before calling #email"
11
+ index = parse_index(match[1])
12
+ email_has_fields?(@emails[index], fields) ? @emails[index] : nil
13
+ end
14
+
15
+ def email_has_fields?(email, fields)
16
+ parse_fields(fields).each do |key, val|
17
+ return false unless (Array(email.send(key)) & Array(val)).any?
18
+ end
19
+ true
20
+ end
21
+
22
+ protected
23
+ # Saves the emails out to RAILS_ROOT/tmp/ and opens it in the default
24
+ # web browser if on OS X. (depends on webrat)
25
+ def save_and_open_emails
26
+ emails_to_open = @emails || emails
27
+ filename = "#{RAILS_ROOT}/tmp/webrat-email-#{Time.now.to_i}.html"
28
+ File.open(filename, "w") do |f|
29
+ emails_to_open.each_with_index do |e, i|
30
+ f.write "<h1>Email #{i+1}</h1><pre>#{e}</pre><hr />"
31
+ end
32
+ end
33
+ open_in_browser(filename)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,18 @@
1
+ module Pickle
2
+ module Email
3
+ # add ability to parse emails
4
+ module Parser
5
+ def match_email
6
+ "(?:#{match_prefix}?(?:#{match_index} )?email)"
7
+ end
8
+
9
+ def capture_email
10
+ "(#{match_email})"
11
+ end
12
+
13
+ def capture_index_in_email
14
+ "(?:#{match_prefix}?(?:#{capture_index} )?email)"
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,13 @@
1
+ require 'pickle'
2
+ require 'pickle/email'
3
+ require 'pickle/email/parser'
4
+
5
+ # add email parser expressions
6
+ Pickle::Parser.send :include, Pickle::Email::Parser
7
+
8
+ World(Pickle::Email)
9
+
10
+ # shortcuts for use in step regexps
11
+ class << self
12
+ delegate :capture_email, :to => 'Pickle.parser'
13
+ end
@@ -0,0 +1,65 @@
1
+ require 'pickle/parser/matchers'
2
+
3
+ module Pickle
4
+ class Parser
5
+ include Matchers
6
+
7
+ attr_reader :config
8
+
9
+ def initialize(options = {})
10
+ @config = options[:config] || raise(ArgumentError, "Parser.new requires a :config")
11
+ end
12
+
13
+ # given a string like 'foo: "bar", bar: "baz"' returns {"foo" => "bar", "bar" => "baz"}
14
+ def parse_fields(fields)
15
+ if fields.blank?
16
+ {}
17
+ elsif fields =~ /^#{match_fields}$/
18
+ fields.scan(/(#{match_field})(?:,|$)/).inject({}) do |m, match|
19
+ m.merge(parse_field(match[0]))
20
+ end
21
+ else
22
+ raise ArgumentError, "The fields string is not in the correct format.\n\n'#{fields}' did not match: #{match_fields}"
23
+ end
24
+ end
25
+
26
+ # given a string like 'foo: expr' returns {key => value}
27
+ def parse_field(field)
28
+ if field =~ /^#{capture_key_and_value_in_field}$/
29
+ { $1 => eval($2) }
30
+ else
31
+ raise ArgumentError, "The field argument is not in the correct format.\n\n'#{field}' did not match: #{match_field}"
32
+ end
33
+ end
34
+
35
+ # returns really underscored name
36
+ def canonical(str)
37
+ str.to_s.underscore.gsub(' ','_').gsub('/','_')
38
+ end
39
+
40
+ # return [factory_name, name or integer index]
41
+ def parse_model(model_name)
42
+ apply_mappings!(model_name)
43
+ if /#{capture_index} #{capture_factory}$/ =~ model_name
44
+ [canonical($2), parse_index($1)]
45
+ elsif /#{capture_factory}#{capture_name_in_label}?$/ =~ model_name
46
+ [canonical($1), canonical($2)]
47
+ end
48
+ end
49
+
50
+ def parse_index(index)
51
+ case index
52
+ when nil, '', 'last' then -1
53
+ when /#{capture_number_in_ordinal}/ then $1.to_i - 1
54
+ when 'first' then 0
55
+ end
56
+ end
57
+
58
+ private
59
+ def apply_mappings!(string)
60
+ config.mappings.each do |mapping|
61
+ string.sub! /^#{mapping.search}$/, mapping.replace
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,87 @@
1
+ module Pickle
2
+ class Parser
3
+ module Matchers
4
+ def match_ordinal
5
+ '(?:\d+(?:st|nd|rd|th))'
6
+ end
7
+
8
+ def match_index
9
+ "(?:first|last|#{match_ordinal})"
10
+ end
11
+
12
+ def match_prefix
13
+ '(?:(?:a|an|another|the|that) )'
14
+ end
15
+
16
+ def match_quoted
17
+ '(?:[^\\"]|\\.)*'
18
+ end
19
+
20
+ def match_label
21
+ "(?::? \"#{match_quoted}\")"
22
+ end
23
+
24
+ def match_value
25
+ "(?:\"#{match_quoted}\"|true|false|\\d+(?:\\.\\d+)?)"
26
+ end
27
+
28
+ def match_field
29
+ "(?:\\w+: #{match_value})"
30
+ end
31
+
32
+ def match_fields
33
+ "(?:#{match_field}, )*#{match_field}"
34
+ end
35
+
36
+ def match_mapping
37
+ "(?:#{config.mappings.map(&:search).join('|')})"
38
+ end
39
+
40
+ def match_factory
41
+ "(?:#{config.factories.keys.map{|n| n.gsub('_','[_ ]')}.join('|')})"
42
+ end
43
+
44
+ def match_plural_factory
45
+ "(?:#{config.factories.keys.map{|n| n.pluralize.gsub('_','[_ ]')}.join('|')})"
46
+ end
47
+
48
+ def match_indexed_model
49
+ "(?:(?:#{match_index} )?#{match_factory})"
50
+ end
51
+
52
+ def match_labeled_model
53
+ "(?:#{match_factory}#{match_label})"
54
+ end
55
+
56
+ def match_model
57
+ "(?:#{match_mapping}|#{match_prefix}?(?:#{match_indexed_model}|#{match_labeled_model}))"
58
+ end
59
+
60
+ def match_predicate
61
+ "(?:#{config.predicates.map{|m| m.sub(/\?$/,'').gsub('_','[_ ]')}.join('|')})"
62
+ end
63
+
64
+ # create capture analogues of match methods
65
+ instance_methods.select{|m| m =~ /^match_/}.each do |method|
66
+ eval <<-end_eval
67
+ def #{method.sub('match_', 'capture_')} # def capture_field
68
+ "(" + #{method} + ")" # "(" + match_field + ")"
69
+ end # end
70
+ end_eval
71
+ end
72
+
73
+ # special capture methods
74
+ def capture_number_in_ordinal
75
+ '(?:(\d+)(?:st|nd|rd|th))'
76
+ end
77
+
78
+ def capture_name_in_label
79
+ "(?::? \"(#{match_quoted})\")"
80
+ end
81
+
82
+ def capture_key_and_value_in_field
83
+ "(?:(\\w+): #{capture_value})"
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,44 @@
1
+ module Pickle
2
+ module Path
3
+ # given args of pickle model name, and an optional extra action, or segment, will attempt to find
4
+ # a matching named route
5
+ #
6
+ # path_to_pickle 'the user', :action => 'edit' # => /users/3/edit
7
+ # path_to_pickle 'the user', 'the comment' # => /users/3/comments/1
8
+ # path_to_pickle 'the user', :segment => 'comments' # => /users/3/comments
9
+ #
10
+ # If you don;t know if the 'extra' part of the path is an action or a segment, then just
11
+ # pass it as 'extra' and this method will run through the possibilities
12
+ #
13
+ # path_to_pickle 'the user', :extra => 'new comment' # => /users/3/comments/new
14
+ def path_to_pickle(*pickle_names)
15
+ options = pickle_names.extract_options!
16
+ models = pickle_names.map{|m| model!(m)}
17
+ if options[:extra]
18
+ parts = options[:extra].underscore.gsub(' ','_').split("_")
19
+ find_pickle_path_using_action_segment_combinations(models, parts)
20
+ else
21
+ pickle_path_for_models_action_segment(models, options[:action], options[:segment])
22
+ end or raise "Could not figure out a path for #{pickle_names.inspect} #{options.inspect}"
23
+ end
24
+
25
+ protected
26
+ def find_pickle_path_using_action_segment_combinations(models, parts)
27
+ path = nil
28
+ (0..parts.length).each do |idx|
29
+ action = parts.slice(0, idx).join('_')
30
+ segment = parts.slice(idx, parts.length).join('_')
31
+ path = pickle_path_for_models_action_segment(models, action, segment) and break
32
+ end
33
+ path
34
+ end
35
+
36
+ def pickle_path_for_models_action_segment(models, action, segment)
37
+ action.blank? or action = action.downcase.gsub(' ','_')
38
+ segment.blank? or segment = segment.downcase.gsub(' ','_')
39
+ model_names = models.map{|m| m.class.name.underscore}.join("_")
40
+ parts = [action, model_names, segment].reject(&:blank?)
41
+ send("#{parts.join('_')}_path", *models) rescue nil
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,5 @@
1
+ require 'pickle'
2
+ require 'pickle/path'
3
+
4
+ # make world pickle/path aware
5
+ World(Pickle::Path)
@@ -0,0 +1,151 @@
1
+ module Pickle
2
+ module Session
3
+ class << self
4
+ def included(world_class)
5
+ proxy_to_pickle_parser(world_class)
6
+ end
7
+
8
+ def extended(world_object)
9
+ proxy_to_pickle_parser(class << world_object; self; end) # metaclass is not 2.1 compatible
10
+ end
11
+
12
+ protected
13
+ def proxy_to_pickle_parser(world_class)
14
+ world_class.class_eval do
15
+ unless methods.include?('method_missing_with_pickle_parser')
16
+ alias_method_chain :method_missing, :pickle_parser
17
+ alias_method_chain :respond_to?, :pickle_parser
18
+ end
19
+ end
20
+ end
21
+ end
22
+
23
+ def create_model(a_model_name, fields = nil)
24
+ factory, label = *parse_model(a_model_name)
25
+ raise ArgumentError, "Can't create with an ordinal (e.g. 1st user)" if label.is_a?(Integer)
26
+ record = pickle_config.factories[factory].create(parse_fields(fields))
27
+ store_model(factory, label, record)
28
+ end
29
+
30
+ def find_model(a_model_name, fields = nil)
31
+ factory, name = *parse_model(a_model_name)
32
+ raise ArgumentError, "Can't find a model with an ordinal (e.g. 1st user)" if name.is_a?(Integer)
33
+ model_class = pickle_config.factories[factory].klass
34
+ if record = model_class.find(:first, :conditions => convert_models_to_attributes(model_class, parse_fields(fields)))
35
+ store_model(factory, name, record)
36
+ end
37
+ end
38
+
39
+ def find_models(factory, fields = nil)
40
+ models_by_index(factory).clear
41
+ model_class = pickle_config.factories[factory].klass
42
+ records = model_class.find(:all, :conditions => convert_models_to_attributes(model_class, parse_fields(fields)))
43
+ records.each {|record| store_model(factory, nil, record)}
44
+ end
45
+
46
+ # return the original model stored by create_model or find_model
47
+ def created_model(name)
48
+ factory, name_or_index = *parse_model(name)
49
+
50
+ if name_or_index.blank?
51
+ models_by_index(factory).last
52
+ elsif name_or_index.is_a?(Integer)
53
+ models_by_index(factory)[name_or_index]
54
+ else
55
+ models_by_name(factory)[name_or_index] or raise "model: #{name} does not refer to known model in this scenario"
56
+ end
57
+ end
58
+
59
+ # predicate version which raises no errors
60
+ def created_model?(name)
61
+ (created_model(name) rescue nil) ? true : false
62
+ end
63
+
64
+ # return a newly selected model
65
+ def model(name)
66
+ (model = created_model(name)) && model.class.find(model.id)
67
+ end
68
+
69
+ # predicate version which raises no errors
70
+ def model?(name)
71
+ (model(name) rescue nil) ? true : false
72
+ end
73
+
74
+ # like model, but raise an error if it can't be found
75
+ def model!(name)
76
+ model(name) or raise "Can't find pickle model: '#{name}' in this scenario"
77
+ end
78
+
79
+ # like created_model, but raise an error if it can't be found
80
+ def created_model!(name)
81
+ created_model(name) or raise "Can't find pickle model: '#{name}' in this scenario"
82
+ end
83
+
84
+ # return all original models of specified type
85
+ def created_models(factory)
86
+ models_by_index(factory)
87
+ end
88
+
89
+ # return all models of specified type (freshly selected from the database)
90
+ def models(factory)
91
+ created_models(factory).map{|model| model.class.find(model.id) }
92
+ end
93
+
94
+ def respond_to_with_pickle_parser?(method, include_private = false)
95
+ respond_to_without_pickle_parser?(method, include_private) || pickle_parser.respond_to?(method, include_private)
96
+ end
97
+
98
+ protected
99
+ def method_missing_with_pickle_parser(method, *args, &block)
100
+ if pickle_parser.respond_to?(method)
101
+ pickle_parser.send(method, *args, &block)
102
+ else
103
+ method_missing_without_pickle_parser(method, *args, &block)
104
+ end
105
+ end
106
+
107
+ def pickle_parser=(parser)
108
+ parser.session = self
109
+ @pickle_parser = parser
110
+ end
111
+
112
+ def pickle_parser
113
+ @pickle_parser or self.pickle_parser = Pickle.parser
114
+ end
115
+
116
+ def pickle_config
117
+ pickle_parser.config
118
+ end
119
+
120
+ def convert_models_to_attributes(ar_class, attrs)
121
+ attrs.each do |key, val|
122
+ if val.is_a?(ActiveRecord::Base) && ar_class.column_names.include?("#{key}_id")
123
+ attrs["#{key}_id"] = val.id
124
+ attrs["#{key}_type"] = val.class.name if ar_class.column_names.include?("#{key}_type")
125
+ attrs.delete(key)
126
+ end
127
+ end
128
+ end
129
+
130
+ def models_by_name(factory)
131
+ @models_by_name ||= {}
132
+ @models_by_name[pickle_parser.canonical(factory)] ||= {}
133
+ end
134
+
135
+ def models_by_index(factory)
136
+ @models_by_index ||= {}
137
+ @models_by_index[pickle_parser.canonical(factory)] ||= []
138
+ end
139
+
140
+ # if the factory name != the model name, store under both names
141
+ def store_model(factory, name, record)
142
+ store_record(record.class.name, name, record) unless pickle_parser.canonical(factory) == pickle_parser.canonical(record.class.name)
143
+ store_record(factory, name, record)
144
+ end
145
+
146
+ def store_record(factory, name, record)
147
+ models_by_name(factory)[name] = record
148
+ models_by_index(factory) << record
149
+ end
150
+ end
151
+ end