Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Kind of messy, but idea is to be able to sanely retrive params
- # with a default, this could be expanded to multi-level params too
- # although I think that, in general, those would require more special-cases.
- # Note: +default+ will be converted to a string; it should be symmetrical
- # with the conversion method
- #
- # While this is extremely helpful for things such as seach forms it
- # seems much less useful dealing with crud operations when Models
- # or AR operations based on an id are used as these are already
- # appropriately handle conversions.
- #
- class SelectParams
- def initialize(source)
- @source = source
- @used = HashWithIndifferentAccess.new
- end
- def get(name, default='', conversion=nil)
- @used[name] = true
- raw_value = @source[name]
- value = raw_value.nil? || raw_value.empty? ? default.to_s : raw_value
- conversion ? value.send(conversion) : value
- end
- # Delete params which have not been retrieved with #get. Useful if the params
- # are going to be directly passed (such as a paginators "next page" link)
- def delete_unused!
- @source.delete_if {|k, v| not @used.include? k}
- end
- def delete(*names)
- names.each {|name| @source.delete name}
- end
- end
- def select_params(source=params)
- p = SelectParams.new(source)
- yield p
- p
- end
- select_params do |p|
- @advanced = p.get :advanced, false, :to_bool
- @search = p.get :search
- if @advanced
- @min_length = p.get :min_length, 0, :to_i
- @max_length = p.get :max_length, 0, :to_i
- @offensive = p.get :include_offensive, false, :to_bool
- @random = p.get :random, false, :to_bool
- @per_page = p.get :per_page, 10, :to_i
- else
- @per_page = 10
- end
- @page = p.get :page, 1, :to_i
- p.delete :commit
- p.delete_unused!
- end
Add Comment
Please, Sign In to add comment