record_select 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 56baa2b6997087a496daf01af6384627370a645e
4
+ data.tar.gz: 65185867eb2f412ba164039caccf350a682a8a69
5
+ SHA512:
6
+ metadata.gz: 6797a1f891e0b7004c40bcd5ac67a66faf80a0b3b956de0d24f41d3c9856d59994f47d8f50c18a5876a50a5d77851119484808d6370f9e5f5c9e63d97ded3447
7
+ data.tar.gz: 670ce6a3107aacd640969f403f3bf9f5c762d6dcd73b6d3215ffe9fdbf50c5190a1cd3d62760536ff454ea5132896dce39e5d6d6ec716bb5660c13b850ba7fb0
@@ -0,0 +1,3 @@
1
+ module RecordselectCustom
2
+ VERSION = "0.0.4"
3
+ end
@@ -0,0 +1,60 @@
1
+ module RecordSelect
2
+ module Actions
3
+ # :method => :get
4
+ # params => [:page, :search]
5
+ def browse
6
+ conditions = record_select_conditions
7
+ klass = record_select_config.model
8
+ count = klass.count(:conditions => conditions, :include => record_select_includes)
9
+ pager = ::Paginator.new(count, (params[:per_page] || record_select_config.per_page).to_i) do |offset, per_page|
10
+ klass.find(:all,
11
+ :offset => offset,
12
+ :include => [record_select_includes, record_select_config.include].flatten.compact,
13
+ :limit => per_page,
14
+ :conditions => conditions,
15
+ :order => record_select_config.order_by
16
+ )
17
+ end
18
+ @page = pager.page(params[:page] || 1)
19
+
20
+ render_record_select((params[:update] ? 'browse.rjs' : '_browse.rhtml')) and return if params[:format] == "js"
21
+ render_record_select '_browse.rhtml', :layout => true
22
+ end
23
+
24
+ # :method => :post
25
+ # params => [:id]
26
+ def select
27
+ klass = record_select_config.model
28
+ record = klass.find(params[:id])
29
+ if record_select_config.notify.is_a? Proc
30
+ record_select_config.notify.call(record)
31
+ elsif record_select_config.notify
32
+ send(record_select_config.notify, record)
33
+ end
34
+ render :nothing => true
35
+ end
36
+
37
+ protected
38
+
39
+ def record_select_config #:nodoc:
40
+ self.class.record_select_config
41
+ end
42
+
43
+ def render_record_select(file, options = {}) #:nodoc:
44
+ options[:layout] ||= false
45
+ options[:file] = record_select_path_of(file)
46
+ options[:use_full_path] = false
47
+ render options
48
+ end
49
+
50
+ private
51
+
52
+ def record_select_views_path
53
+ @record_select_views_path ||= "vendor/plugins/#{File.expand_path(__FILE__).match(/vendor\/plugins\/(\w*)/)[1]}/lib/views"
54
+ end
55
+
56
+ def record_select_path_of(template)
57
+ File.join(RAILS_ROOT, record_select_views_path, template)
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,88 @@
1
+ module RecordSelect
2
+ module Conditions
3
+ protected
4
+ # returns the combination of all conditions.
5
+ # conditions come from:
6
+ # * current search (params[:search])
7
+ # * intelligent url params (e.g. params[:first_name] if first_name is a model column)
8
+ # * specific conditions supplied by the developer
9
+ def record_select_conditions
10
+ conditions = []
11
+
12
+ merge_conditions(
13
+ record_select_conditions_from_search,
14
+ record_select_conditions_from_params,
15
+ record_select_conditions_from_controller
16
+ )
17
+ end
18
+
19
+ # an override method.
20
+ # here you can provide custom conditions to define the selectable records. useful for situational restrictions.
21
+ def record_select_conditions_from_controller; end
22
+
23
+ # another override method.
24
+ # define any association includes you want for the finder search.
25
+ def record_select_includes; end
26
+
27
+ # generate conditions from params[:search]
28
+ # override this if you want to customize the search routine
29
+ def record_select_conditions_from_search
30
+ search_pattern = record_select_config.full_text_search? ? '%?%' : '?%'
31
+
32
+ if params[:search] and !params[:search].strip.empty?
33
+ tokens = params[:search].strip.split(' ')
34
+
35
+ where_clauses = record_select_config.search_on.collect { |sql| "#{sql} LIKE ?" }
36
+ phrase = "(#{where_clauses.join(' OR ')})"
37
+
38
+ sql = ([phrase] * tokens.length).join(' AND ')
39
+ tokens = tokens.collect{ |value| [search_pattern.sub('?', value.downcase)] * record_select_config.search_on.length }.flatten
40
+
41
+ conditions = [sql, *tokens]
42
+ end
43
+ end
44
+
45
+ # instead of a shotgun approach, this assumes the user is
46
+ # searching vs some SQL field (possibly built with CONCAT())
47
+ # similar to the record labels.
48
+ # def record_select_simple_conditions_from_search
49
+ # return unless params[:search] and not params[:search].empty?
50
+ #
51
+ # search_pattern = record_select_config.full_text_search? ? '%?%' : '?%'
52
+ # search_string = search_pattern.sub('?', value.downcase)
53
+ #
54
+ # ["LOWER(#{record_select_config.search_on})", search_pattern.sub('?', value.downcase)]
55
+ # end
56
+
57
+ # generate conditions from the url parameters (e.g. users/browse?group_id=5)
58
+ def record_select_conditions_from_params
59
+ conditions = nil
60
+ params.each do |field, value|
61
+ next unless column = record_select_config.model.columns_hash[field]
62
+ conditions = merge_conditions(
63
+ conditions,
64
+ record_select_condition_for_column(column, value)
65
+ )
66
+ end
67
+ conditions
68
+ end
69
+
70
+ # generates an SQL condition for the given column/value
71
+ def record_select_condition_for_column(column, value)
72
+ if value.blank? and column.null
73
+ "#{column.name} IS NULL"
74
+ elsif value.is_a?(Array)
75
+ ["#{column.name} IN (?)", value.map{|v| column.type_cast(v)}]
76
+ elsif column.text?
77
+ ["LOWER(#{column.name}) LIKE ?", value]
78
+ else
79
+ ["#{column.name} = ?", column.type_cast(value)]
80
+ end
81
+ end
82
+
83
+ def merge_conditions(*conditions) #:nodoc:
84
+ c = conditions.find_all {|c| not c.nil? and not c.empty? }
85
+ c.empty? ? nil : c.collect{|c| record_select_config.model.send(:sanitize_sql, c)}.join(' AND ')
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,84 @@
1
+ module RecordSelect
2
+ # a write-once configuration object
3
+ class Config
4
+ def initialize(klass, options = {})
5
+ @klass = klass
6
+
7
+ @notify = block_given? ? proc : options[:notify]
8
+
9
+ @per_page = options[:per_page]
10
+
11
+ @search_on = [options[:search_on]].flatten
12
+
13
+ @order_by = options[:order_by]
14
+
15
+ @full_text_search = options[:full_text_search]
16
+
17
+ @label = options[:label]
18
+
19
+ @include = options[:include]
20
+ end
21
+
22
+ # The model object we're browsing
23
+ def model
24
+ @model ||= klass.to_s.camelcase.constantize
25
+ end
26
+
27
+ # Records to show on a page
28
+ def per_page
29
+ @per_page ||= 10
30
+ end
31
+
32
+ # The method name or proc to notify of a selection event.
33
+ # May not matter if the selection event is intercepted client-side.
34
+ def notify
35
+ @notify
36
+ end
37
+
38
+ # A collection of fields to search. This is essentially raw SQL, so you could search on "CONCAT(first_name, ' ', last_name)" if you wanted to.
39
+ # NOTE: this does *NO* default transforms (such as LOWER()), that's left entirely up to you.
40
+ def search_on
41
+ @search_on ||= self.model.columns.collect{|c| c.name if [:text, :string].include? c.type}.compact
42
+ end
43
+
44
+ def order_by
45
+ @order_by ||= "#{model.primary_key} ASC"
46
+ end
47
+
48
+ def full_text_search?
49
+ @full_text_search ? true : false
50
+ end
51
+
52
+ def include
53
+ @include
54
+ end
55
+
56
+ # If a proc, must accept the record as an argument and return a descriptive string.
57
+ #
58
+ # If a symbol or string, must name a partial that renders a representation of the
59
+ # record. The partial should assume a local "record" variable, and should include a
60
+ # <label> tag, even if it's not visible. The contents of the <label> tag will be used
61
+ # to represent the record once it has been selected. For example:
62
+ #
63
+ # record_select_config.label = :user_description
64
+ #
65
+ # > app/views/users/_user_description.erb
66
+ #
67
+ # <div class="user_description">
68
+ # <%= image_tag url_for_file_column(record, 'avatar') %>
69
+ # <label><%= record.username %></label>
70
+ # <p><%= record.quote %></p>
71
+ # </div>
72
+ #
73
+ def label
74
+ @label ||= proc {|r| r.to_label}
75
+ end
76
+
77
+ protected
78
+
79
+ # A singularized underscored version of the model we're browsing
80
+ def klass
81
+ @klass
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,25 @@
1
+ module RecordSelect
2
+ module FormBuilder
3
+ def record_select(association, options = {})
4
+ reflection = @object.class.reflect_on_association(association)
5
+ form_name = form_name_for_association(reflection)
6
+ current = @object.send(association)
7
+ options[:id] ||= "#{@object_name.gsub(/[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")}_#{association}"
8
+
9
+ if [:has_one, :belongs_to].include? reflection.macro
10
+ @template.record_select_field(form_name, current || reflection.klass.new, options)
11
+ else
12
+ options[:controller] ||= reflection.klass.to_s.pluralize.underscore
13
+ @template.record_multi_select_field(form_name, current, options)
14
+ end
15
+ end
16
+
17
+ private
18
+
19
+ def form_name_for_association(reflection)
20
+ key_name = (reflection.options[:foreign_key] || reflection.association_foreign_key)
21
+ key_name += "s" unless [:has_one, :belongs_to].include? reflection.macro
22
+ form_name = "#{@object_name}[#{key_name}]"
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,187 @@
1
+ module RecordSelect
2
+ module Helpers
3
+ # Print this from your layout to include everything necessary for RecordSelect to work.
4
+ # Well, not everything. You need Prototype too.
5
+ def record_select_includes
6
+ includes = ''
7
+ includes << stylesheet_link_tag('record_select/record_select')
8
+ includes << javascript_include_tag('record_select/record_select')
9
+ includes
10
+ end
11
+
12
+ # Adds a link on the page that toggles a RecordSelect widget from the given controller.
13
+ #
14
+ # *Options*
15
+ # +onselect+:: JavaScript code to handle selections client-side. This code has access to two variables: id, label. If the code returns false, the dialog will *not* close automatically.
16
+ # +params+:: Extra URL parameters. If any parameter is a column name, the parameter will be used as a search term to filter the result set.
17
+ def link_to_record_select(name, controller, options = {})
18
+ options[:params] ||= {}
19
+ options[:params].merge!(:controller => controller, :action => :browse)
20
+ options[:onselect] = "function(id, label) {#{options[:onselect]}}" if options[:onselect]
21
+ options[:html] ||= {}
22
+ options[:html][:id] ||= "rs_#{rand(9999)}"
23
+
24
+ assert_controller_responds(options[:params][:controller])
25
+
26
+ html = link_to_function(name, '', options[:html])
27
+ html << javascript_tag("new RecordSelect.Dialog(#{options[:html][:id].to_json}, #{url_for(options[:params].merge(:escape => false)).to_json}, {onselect: #{options[:onselect] || ''}})")
28
+
29
+ return html
30
+ end
31
+
32
+ # Adds a RecordSelect-based form field. The field submits the record's id using a hidden input.
33
+ #
34
+ # *Arguments*
35
+ # +name+:: the input name that will be used to submit the selected record's id.
36
+ # +current+:: the currently selected object. provide a new record if there're none currently selected and you have not passed the optional :controller argument.
37
+ #
38
+ # *Options*
39
+ # +controller+:: The controller configured to provide the result set. Optional if you have standard resource controllers (e.g. UsersController for the User model), in which case the controller will be inferred from the class of +current+ (the second argument)
40
+ # +params+:: A hash of extra URL parameters
41
+ # +id+:: The id to use for the input. Defaults based on the input's name.
42
+ # +onchange+:: A JavaScript function that will be called whenever something new is selected. It should accept the new id as the first argument, and the new label as the second argument. For example, you could set onchange to be "function(id, label) {alert(id);}", or you could create a JavaScript function somewhere else and set onchange to be "my_function" (without the parantheses!).
43
+ def record_select_field(name, current, options = {})
44
+ options[:controller] ||= current.class.to_s.pluralize.underscore
45
+ options[:params] ||= {}
46
+ options[:id] ||= name.gsub(/[\[\]]/, '_')
47
+ options[:js_params] ||= "null"
48
+ options[:ass_value] = true if options[:ass_value].nil?
49
+
50
+ controller = assert_controller_responds(options[:controller])
51
+
52
+ id = label = ''
53
+ if options[:ass_value]
54
+ if current and not current.new_record?
55
+ id = current.id
56
+ label = label_for_field(current, controller)
57
+ end
58
+ else
59
+ id = current.object_id
60
+ label = current
61
+ end
62
+
63
+ url = url_for({:action => :browse, :controller => options[:controller], :escape => false, :format => :js}.merge(options[:params]))
64
+
65
+ html = text_field_tag(name, nil, :autocomplete => 'off', :id => options[:id], :class => options[:class],
66
+ :onfocus => "this.focused=true", :onblur => "this.focused=false", :placeholder => options[:placeholder])
67
+ html << javascript_tag("jQuery(#{("#"+options[:id]).to_json}).recordSelectSingle(#{url.to_json}, {
68
+ id: #{id.to_json},
69
+ label: #{label.to_json},
70
+ ass_value: #{options[:ass_value]},
71
+ openEvents: #{options[:open_events].try(:to_json) || 'null'},
72
+ onchange: #{options[:onchange] || ''.to_json},
73
+ js_params: #{options[:js_params]}
74
+ });")
75
+
76
+ return html
77
+ end
78
+
79
+ # Assists with the creation of an observer for the :onchange option of the record_select_field method.
80
+ # Currently only supports building an Ajax.Request based on the id of the selected record.
81
+ #
82
+ # options[:url] should be a hash with all the necessary options *except* :id. that parameter
83
+ # will be provided based on the selected record.
84
+ #
85
+ # Question: if selecting users, what's more likely?
86
+ # /users/5/categories
87
+ # /categories?user_id=5
88
+ def record_select_observer(options = {})
89
+ fn = "function(id, value) {"
90
+ fn << "var url = #{url_for(options[:url].merge(:id => ":id:")).to_json}.replace(/:id:/, id);"
91
+ fn << "jQuery.get(url);"
92
+ fn << "}"
93
+ end
94
+
95
+ # Adds a RecordSelect-based form field for multiple selections. The values submit using a list of hidden inputs.
96
+ #
97
+ # *Arguments*
98
+ # +name+:: the input name that will be used to submit the selected records' ids. empty brackets will be appended to the name.
99
+ # +current+:: pass a collection of existing associated records
100
+ #
101
+ # *Options*
102
+ # +controller+:: The controller configured to provide the result set.
103
+ # +params+:: A hash of extra URL parameters
104
+ # +id+:: The id to use for the input. Defaults based on the input's name.
105
+ def record_multi_select_field(name, current, options = {})
106
+ options[:controller] ||= current.first.class.to_s.pluralize.underscore
107
+ options[:params] ||= {}
108
+ options[:id] ||= name.gsub(/[\[\]]/, '_')
109
+
110
+ controller = assert_controller_responds(options[:controller])
111
+
112
+ current = current.inject([]) { |memo, record| memo.push({:id => record.id, :label => label_for_field(record, controller)}) }
113
+
114
+ url = url_for({:action => :browse, :controller => options[:controller], :escape => false}.merge(options[:params]))
115
+
116
+ html = text_field_tag("#{name}[]", nil, :autocomplete => 'off', :id => options[:id], :class => options[:class], :onfocus => "this.focused=true", :onblur => "this.focused=false")
117
+ html << content_tag('ul', '', :class => 'record-select-list');
118
+ html << javascript_tag("new RecordSelect.Multiple(#{options[:id].to_json}, #{url.to_json}, {current: #{current.to_json}});")
119
+
120
+ return html
121
+ end
122
+
123
+ # A helper to render RecordSelect partials
124
+ def render_record_select(file, options = {}) #:nodoc:
125
+ options[:file] = controller.send(:record_select_path_of, file)
126
+ options[:use_full_path] = false
127
+ render options
128
+ end
129
+
130
+ # Provides view access to the RecordSelect configuration
131
+ def record_select_config #:nodoc:
132
+ controller.send :record_select_config
133
+ end
134
+
135
+ # The id of the RecordSelect widget for the given controller.
136
+ def record_select_id(controller = nil) #:nodoc:
137
+ controller ||= params[:controller]
138
+ "record-select-#{controller.gsub('/', '_')}"
139
+ end
140
+
141
+ def record_select_search_id(controller = nil) #:nodoc:
142
+ "#{record_select_id(controller)}-search"
143
+ end
144
+
145
+ private
146
+
147
+ # uses renderer (defaults to record_select_config.label) to determine how the given record renders.
148
+ def render_record_from_config(record, renderer = record_select_config.label)
149
+ case renderer
150
+ when Symbol, String
151
+ # return full-html from the named partial
152
+ render :partial => renderer.to_s, :locals => {:record => record}
153
+
154
+ when Proc
155
+ # return an html-cleaned descriptive string
156
+ h renderer.call(record)
157
+ end
158
+ end
159
+
160
+ # uses the result of render_record_from_config to snag an appropriate record label
161
+ # to display in a field.
162
+ #
163
+ # if given a controller, searches for a partial in its views path
164
+ def label_for_field(record, controller = self.controller)
165
+ renderer = controller.record_select_config.label
166
+ case renderer
167
+ when Symbol, String
168
+ # find the <label> element and grab its innerHTML
169
+ description = render_record_from_config(record, File.join(controller.controller_path, renderer.to_s))
170
+ description.match(/<label[^>]*>(.*)<\/label>/)[1]
171
+
172
+ when Proc
173
+ # just return the string
174
+ render_record_from_config(record, renderer)
175
+ end
176
+ end
177
+
178
+ def assert_controller_responds(controller_name)
179
+ controller_name = "#{controller_name.camelize}Controller"
180
+ controller = controller_name.constantize
181
+ unless controller.uses_record_select?
182
+ raise "#{controller_name} has not been configured to use RecordSelect."
183
+ end
184
+ controller
185
+ end
186
+ end
187
+ end
@@ -1,3 +1,3 @@
1
1
  module RecordselectCustom
2
- VERSION = "0.0.3"
2
+ VERSION = "0.0.4"
3
3
  end
metadata CHANGED
@@ -1,35 +1,23 @@
1
- --- !ruby/object:Gem::Specification
1
+ --- !ruby/object:Gem::Specification
2
2
  name: record_select
3
- version: !ruby/object:Gem::Version
4
- hash: 25
5
- prerelease:
6
- segments:
7
- - 0
8
- - 0
9
- - 3
10
- version: 0.0.3
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.4
11
5
  platform: ruby
12
- authors:
6
+ authors:
13
7
  - lion
14
8
  autorequire:
15
9
  bindir: bin
16
10
  cert_chain: []
17
-
18
- date: 2014-12-17 00:00:00 +08:00
19
- default_executable:
11
+ date: 2014-12-17 00:00:00.000000000 Z
20
12
  dependencies: []
21
-
22
13
  description: just for test
23
- email:
14
+ email:
24
15
  - lion3139@gmail.com
25
16
  executables: []
26
-
27
17
  extensions: []
28
-
29
18
  extra_rdoc_files: []
30
-
31
- files:
32
- - .gitignore
19
+ files:
20
+ - ".gitignore"
33
21
  - CHANGELOG
34
22
  - Gemfile
35
23
  - LICENSE.txt
@@ -59,7 +47,13 @@ files:
59
47
  - lib/record_select/config.rb
60
48
  - lib/record_select/form_builder.rb
61
49
  - lib/record_select/helpers.rb
50
+ - lib/record_select/version.rb
62
51
  - lib/recordselect_custom.rb
52
+ - lib/recordselect_custom/actions.rb
53
+ - lib/recordselect_custom/conditions.rb
54
+ - lib/recordselect_custom/config.rb
55
+ - lib/recordselect_custom/form_builder.rb
56
+ - lib/recordselect_custom/helpers.rb
63
57
  - lib/recordselect_custom/version.rb
64
58
  - lib/views/_browse.html
65
59
  - lib/views/_browse.rhtml
@@ -69,39 +63,28 @@ files:
69
63
  - recordselect_custom.gemspec
70
64
  - test/recordselect_test.rb
71
65
  - uninstall.rb
72
- has_rdoc: true
73
- homepage: ""
66
+ homepage: ''
74
67
  licenses: []
75
-
68
+ metadata: {}
76
69
  post_install_message:
77
70
  rdoc_options: []
78
-
79
- require_paths:
71
+ require_paths:
80
72
  - lib
81
- required_ruby_version: !ruby/object:Gem::Requirement
82
- none: false
83
- requirements:
73
+ required_ruby_version: !ruby/object:Gem::Requirement
74
+ requirements:
84
75
  - - ">="
85
- - !ruby/object:Gem::Version
86
- hash: 3
87
- segments:
88
- - 0
89
- version: "0"
90
- required_rubygems_version: !ruby/object:Gem::Requirement
91
- none: false
92
- requirements:
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ requirements:
93
80
  - - ">="
94
- - !ruby/object:Gem::Version
95
- hash: 3
96
- segments:
97
- - 0
98
- version: "0"
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
99
83
  requirements: []
100
-
101
84
  rubyforge_project:
102
- rubygems_version: 1.3.9.5
85
+ rubygems_version: 2.2.2
103
86
  signing_key:
104
- specification_version: 3
87
+ specification_version: 4
105
88
  summary: just for test
106
- test_files:
89
+ test_files:
107
90
  - test/recordselect_test.rb