Class: Tableling::Model
- Inherits:
-
Object
- Object
- Tableling::Model
- Defined in:
- lib/tableling/model.rb
Instance Method Summary collapse
- #field(name, options = {}, &block) ⇒ Object
-
#initialize(options = {}, &block) ⇒ Model
constructor
A new instance of Model.
- #process(params) ⇒ Object
- #quick_search(&block) ⇒ Object
Constructor Details
#initialize(options = {}, &block) ⇒ Model
Returns a new instance of Model.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/tableling/model.rb', line 6 def initialize = {}, &block @field_options = {} @modules = [:modules] || [] @modules = [ @modules ] unless @modules.kind_of?(Array) @modules.each{ |mod| extend mod } initialize_model @fields = [] @field_modules = [:field_modules] || [] @field_modules = [ @field_modules ] unless @field_modules.kind_of?(Array) instance_eval &block if block end |
Instance Method Details
#field(name, options = {}, &block) ⇒ Object
22 23 24 25 26 27 28 |
# File 'lib/tableling/model.rb', line 22 def field name, = {}, &block if field = @fields.find{ |f| f.name.to_s == name.to_s } return field end # TODO: do not add field if it's already there Field.new(name, @field_options.merge({ :modules => @field_modules }).merge(), &block).tap{ |f| @fields << f } end |
#process(params) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/tableling/model.rb', line 34 def process params q = base_query if @quick_search and params[:quick_search].present? q = @quick_search.call q, params[:quick_search].to_s end total = q.count :all if params[:sort].present? params[:sort].select{ |item| item.match /\A([^ ]+)* (asc|desc)\Z/ }.each do |item| parts = item.split ' ' q = field(parts[0]).with_order q, parts[1].to_sym end end limit = params[:page_size].to_i limit = 10 if limit <= 0 q = q.limit limit offset = params[:page].to_i - 1 offset = 0 if offset < 0 q = q.offset offset * limit { :total => total, :data => q.all.collect{ |o| @fields.inject({}){ |memo,f| memo[f.name] = f.extract(o); memo } } } end |
#quick_search(&block) ⇒ Object
30 31 32 |
# File 'lib/tableling/model.rb', line 30 def quick_search &block @quick_search = block end |