Skip to content
Browse files

Init

  • Loading branch information...
0 parents commit 5e3f5b7f794ae0187be3c2bd93fdd84146c61027 @bogdan committed Jun 13, 2011
5 .document
@@ -0,0 +1,5 @@
+lib/**/*.rb
+bin/*
+-
+features/**/*.feature
+LICENSE.txt
7 .gitignore
@@ -0,0 +1,7 @@
+.bundle
+coverage
+rdoc
+.yardoc
+spec.log
+pkg
+
1 .rspec
@@ -0,0 +1 @@
+--color
26 Gemfile
@@ -0,0 +1,26 @@
+source "http://rubygems.org"
+# Add dependencies required to use your gem here.
+# Example:
+# gem "activesupport", ">= 2.3.5"
+
+# Add dependencies to develop your gem here.
+# Include everything needed to run rake, tests, features, etc.
+
+gem "rails"
+
+
+
+group :development do
+ gem "rake", "0.8.7"
+ gem "mocha"
+ gem "rspec", "2.6.0"
+ gem "bundler", "~> 1.0.0"
+ gem "jeweler", "~> 1.6.0"
+ gem "rcov", ">= 0"
+ gem "ruby-debug"
+ gem "sqlite3-ruby"
+ gem "fastercsv"
+ gem "nokogiri"
+ gem 'will_paginate', '2.3.15'
+
+end
111 Gemfile.lock
@@ -0,0 +1,111 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ abstract (1.0.0)
+ actionmailer (3.0.7)
+ actionpack (= 3.0.7)
+ mail (~> 2.2.15)
+ actionpack (3.0.7)
+ activemodel (= 3.0.7)
+ activesupport (= 3.0.7)
+ builder (~> 2.1.2)
+ erubis (~> 2.6.6)
+ i18n (~> 0.5.0)
+ rack (~> 1.2.1)
+ rack-mount (~> 0.6.14)
+ rack-test (~> 0.5.7)
+ tzinfo (~> 0.3.23)
+ activemodel (3.0.7)
+ activesupport (= 3.0.7)
+ builder (~> 2.1.2)
+ i18n (~> 0.5.0)
+ activerecord (3.0.7)
+ activemodel (= 3.0.7)
+ activesupport (= 3.0.7)
+ arel (~> 2.0.2)
+ tzinfo (~> 0.3.23)
+ activeresource (3.0.7)
+ activemodel (= 3.0.7)
+ activesupport (= 3.0.7)
+ activesupport (3.0.7)
+ arel (2.0.10)
+ builder (2.1.2)
+ columnize (0.3.2)
+ diff-lcs (1.1.2)
+ erubis (2.6.6)
+ abstract (>= 1.0.0)
+ fastercsv (1.5.3)
+ git (1.2.5)
+ i18n (0.5.0)
+ jeweler (1.6.1)
+ bundler (~> 1.0.0)
+ git (>= 1.2.5)
+ rake
+ linecache (0.43)
+ mail (2.2.19)
+ activesupport (>= 2.3.6)
+ i18n (>= 0.4.0)
+ mime-types (~> 1.16)
+ treetop (~> 1.4.8)
+ mime-types (1.16)
+ mocha (0.9.12)
+ nokogiri (1.4.4)
+ polyglot (0.3.1)
+ rack (1.2.3)
+ rack-mount (0.6.14)
+ rack (>= 1.0.0)
+ rack-test (0.5.7)
+ rack (>= 1.0)
+ rails (3.0.7)
+ actionmailer (= 3.0.7)
+ actionpack (= 3.0.7)
+ activerecord (= 3.0.7)
+ activeresource (= 3.0.7)
+ activesupport (= 3.0.7)
+ bundler (~> 1.0)
+ railties (= 3.0.7)
+ railties (3.0.7)
+ actionpack (= 3.0.7)
+ activesupport (= 3.0.7)
+ rake (>= 0.8.7)
+ thor (~> 0.14.4)
+ rake (0.8.7)
+ rcov (0.9.9)
+ rspec (2.6.0)
+ rspec-core (~> 2.6.0)
+ rspec-expectations (~> 2.6.0)
+ rspec-mocks (~> 2.6.0)
+ rspec-core (2.6.0)
+ rspec-expectations (2.6.0)
+ diff-lcs (~> 1.1.2)
+ rspec-mocks (2.6.0)
+ ruby-debug (0.10.4)
+ columnize (>= 0.1)
+ ruby-debug-base (~> 0.10.4.0)
+ ruby-debug-base (0.10.4)
+ linecache (>= 0.3)
+ sqlite3 (1.3.3)
+ sqlite3-ruby (1.3.3)
+ sqlite3 (>= 1.3.3)
+ thor (0.14.6)
+ treetop (1.4.9)
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.27)
+ will_paginate (2.3.15)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ bundler (~> 1.0.0)
+ fastercsv
+ jeweler (~> 1.6.0)
+ mocha
+ nokogiri
+ rails
+ rake (= 0.8.7)
+ rcov
+ rspec (= 2.6.0)
+ ruby-debug
+ sqlite3-ruby
+ will_paginate (= 2.3.15)
20 LICENSE.txt
@@ -0,0 +1,20 @@
+Copyright (c) 2011 Bogdan Gusiev
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 README.rdoc
@@ -0,0 +1,19 @@
+= datagrid
+
+Description goes here.
+
+== Contributing to datagrid
+
+* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
+* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
+* Fork the project
+* Start a feature/bugfix branch
+* Commit and push until you are happy with your contribution
+* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
+* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
+
+== Copyright
+
+Copyright (c) 2011 Bogdan Gusiev. See LICENSE.txt for
+further details.
+
49 Rakefile
@@ -0,0 +1,49 @@
+# encoding: utf-8
+
+require 'rubygems'
+require 'bundler'
+begin
+ Bundler.setup(:default, :development)
+rescue Bundler::BundlerError => e
+ $stderr.puts e.message
+ $stderr.puts "Run `bundle install` to install missing gems"
+ exit e.status_code
+end
+require 'rake'
+
+require 'jeweler'
+Jeweler::Tasks.new do |gem|
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
+ gem.name = "datagrid"
+ gem.homepage = "http://github.com/bogdan/datagrid"
+ gem.license = "MIT"
+ gem.summary = %Q{Ruby gem to create datagrids}
+ gem.description = %Q{This allows you to easily build datagrid aka data tables with sortable columns and filters}
+ gem.email = "agresso@gmail.com"
+ gem.authors = ["Bogdan Gusiev"]
+ # dependencies defined in Gemfile
+end
+Jeweler::RubygemsDotOrgTasks.new
+
+require 'rspec/core'
+require 'rspec/core/rake_task'
+RSpec::Core::RakeTask.new(:spec) do |spec|
+ spec.pattern = FileList['spec/**/*_spec.rb']
+end
+
+RSpec::Core::RakeTask.new(:rcov) do |spec|
+ spec.pattern = 'spec/**/*_spec.rb'
+ spec.rcov = true
+end
+
+task :default => :spec
+
+require 'rake/rdoctask'
+Rake::RDocTask.new do |rdoc|
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
+
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = "datagrid #{version}"
+ rdoc.rdoc_files.include('README*')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
88 Readme.md
@@ -0,0 +1,88 @@
+## Datagrid
+
+Ruby library that helps you to build and repsend table like data with:
+
+* Filtering
+* Sort order
+* Exportort to CSV
+
+
+### Grid DSL
+
+In order to create a report You need to define:
+
+* scope of ActiveRecord objects to look through
+* filters that will be used to filter data
+* columns that should be displayed and sortable(if possible)
+
+
+``` ruby
+
+class SimpleReport
+
+ include Datagrid
+
+
+ scope do
+ User.includes(:group)
+ end
+
+ filter(:category, :enum, :select => ["first", "second"])
+ filter(:disabled, :eboolean)
+ filter(:confirmed, :boolean)
+ integer_range_filter(:logins_count, :integer)
+ filter(:group_name) do |value|
+ self.joins(:group).where(:groups => {:name => value})
+ end
+
+ column(:group, :order => "groups.name") do |model|
+ group.name
+ end
+
+ column(:name)
+
+
+end
+
+
+report = SimpleReport.new(:group_id => 5, :from_logins_count => 1, :category => "first")
+report.assets # => Array of User: SELECT * FROM users WHERE users.group_id = 5 AND users.logins_count >= 1 AND users.category = 'first'
+report.header
+report.rows
+report.data
+
+```
+
+### Scope
+
+Default scope of objects to filter and display.
+In common case it is `ActiveRecord::Base` subclass with some generic scopes like in example above.
+
+### Filters
+
+Each filter definition consists of:
+
+* name of the filter
+* type that will be used for value conversion
+* conditions block that cegerates `ActiveRecord` scope
+* additional options
+
+Datagrid supports different type of filters including:
+
+* text
+* integer
+* date
+* boolean
+* eboolean - the select of "yes", "no" and any
+* enum
+
+Read more about filters here:
+
+
+### Columns
+
+Each column is represented by name and code block to calculate the value.
+If no block given the value will be the result of column name method call on object defined in Scope.
+
+
+
1 VERSION
@@ -0,0 +1 @@
+0.0.3
106 datagrid.gemspec
@@ -0,0 +1,106 @@
+# Generated by jeweler
+# DO NOT EDIT THIS FILE DIRECTLY
+# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = %q{datagrid}
+ s.version = "0.0.3"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.authors = ["Bogdan Gusiev"]
+ s.date = %q{2011-06-02}
+ s.description = %q{This allows you to easily build datagrid aka data tables with sortable columns and filters}
+ s.email = %q{agresso@gmail.com}
+ s.extra_rdoc_files = [
+ "LICENSE.txt",
+ "README.rdoc"
+ ]
+ s.files = [
+ ".document",
+ ".rspec",
+ "Gemfile",
+ "Gemfile.lock",
+ "LICENSE.txt",
+ "README.rdoc",
+ "Rakefile",
+ "VERSION",
+ "datagrid.gemspec",
+ "lib/datagrid.rb",
+ "lib/datagrid/columns.rb",
+ "lib/datagrid/columns/column.rb",
+ "lib/datagrid/core.rb",
+ "lib/datagrid/filters.rb",
+ "lib/datagrid/filters/base_filter.rb",
+ "lib/datagrid/filters/boolean_enum_filter.rb",
+ "lib/datagrid/filters/boolean_filter.rb",
+ "lib/datagrid/filters/composite_filters.rb",
+ "lib/datagrid/filters/date_filter.rb",
+ "lib/datagrid/filters/default_filter.rb",
+ "lib/datagrid/filters/enum_filter.rb",
+ "lib/datagrid/filters/filter_eval.rb",
+ "lib/datagrid/filters/integer_filter.rb",
+ "lib/datagrid/form_builder.rb",
+ "lib/datagrid/helper.rb",
+ "lib/datagrid/rspec.rb",
+ "spec/datagrid_spec.rb",
+ "spec/simple_report_spec.rb",
+ "spec/spec_helper.rb",
+ "tags"
+ ]
+ s.homepage = %q{http://github.com/bogdan/datagrid}
+ s.licenses = ["MIT"]
+ s.require_paths = ["lib"]
+ s.rubygems_version = %q{1.3.7}
+ s.summary = %q{Ruby gem to create datagrids}
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 3
+
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
+ s.add_runtime_dependency(%q<rails>, [">= 0"])
+ s.add_development_dependency(%q<rake>, ["= 0.8.7"])
+ s.add_development_dependency(%q<mocha>, [">= 0"])
+ s.add_development_dependency(%q<rspec-rails>, ["= 2.6.0"])
+ s.add_development_dependency(%q<rspec>, ["= 2.6.0"])
+ s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
+ s.add_development_dependency(%q<jeweler>, ["~> 1.6.0"])
+ s.add_development_dependency(%q<rcov>, [">= 0"])
+ s.add_development_dependency(%q<ruby-debug>, [">= 0"])
+ s.add_development_dependency(%q<sqlite3-ruby>, [">= 0"])
+ s.add_development_dependency(%q<fastercsv>, [">= 0"])
+ s.add_development_dependency(%q<nokogiri>, [">= 0"])
+ s.add_development_dependency(%q<will_paginate>, ["= 2.3.15"])
+ else
+ s.add_dependency(%q<rails>, [">= 0"])
+ s.add_dependency(%q<rake>, ["= 0.8.7"])
+ s.add_dependency(%q<mocha>, [">= 0"])
+ s.add_dependency(%q<rspec-rails>, ["= 2.6.0"])
+ s.add_dependency(%q<rspec>, ["= 2.6.0"])
+ s.add_dependency(%q<bundler>, ["~> 1.0.0"])
+ s.add_dependency(%q<jeweler>, ["~> 1.6.0"])
+ s.add_dependency(%q<rcov>, [">= 0"])
+ s.add_dependency(%q<ruby-debug>, [">= 0"])
+ s.add_dependency(%q<sqlite3-ruby>, [">= 0"])
+ s.add_dependency(%q<fastercsv>, [">= 0"])
+ s.add_dependency(%q<nokogiri>, [">= 0"])
+ s.add_dependency(%q<will_paginate>, ["= 2.3.15"])
+ end
+ else
+ s.add_dependency(%q<rails>, [">= 0"])
+ s.add_dependency(%q<rake>, ["= 0.8.7"])
+ s.add_dependency(%q<mocha>, [">= 0"])
+ s.add_dependency(%q<rspec-rails>, ["= 2.6.0"])
+ s.add_dependency(%q<rspec>, ["= 2.6.0"])
+ s.add_dependency(%q<bundler>, ["~> 1.0.0"])
+ s.add_dependency(%q<jeweler>, ["~> 1.6.0"])
+ s.add_dependency(%q<rcov>, [">= 0"])
+ s.add_dependency(%q<ruby-debug>, [">= 0"])
+ s.add_dependency(%q<sqlite3-ruby>, [">= 0"])
+ s.add_dependency(%q<fastercsv>, [">= 0"])
+ s.add_dependency(%q<nokogiri>, [">= 0"])
+ s.add_dependency(%q<will_paginate>, ["= 2.3.15"])
+ end
+end
+
37 lib/datagrid.rb
@@ -0,0 +1,37 @@
+require "datagrid/filters"
+require "datagrid/columns"
+require "datagrid/core"
+
+require "datagrid/helper"
+require "datagrid/form_builder"
+
+module Datagrid
+
+ def self.included(base)
+ base.extend ClassMethods
+ base.class_eval do
+
+ include ::Datagrid::Core
+ include ::Datagrid::Filters
+ include ::Datagrid::Columns
+
+ end
+ base.send :include, InstanceMethods
+ end # self.included
+
+ module ClassMethods
+
+
+ end # ClassMethods
+
+ module InstanceMethods
+
+ end # InstanceMethods
+
+ class ConfigurationError < StandardError; end
+
+
+end
+
+
+
105 lib/datagrid/columns.rb
@@ -0,0 +1,105 @@
+module Datagrid
+
+ class OrderUnsupported < StandardError
+ end
+
+ module Columns
+ require "datagrid/columns/column"
+
+ def self.included(base)
+ base.extend ClassMethods
+ base.class_eval do
+
+ include Datagrid::Core
+
+ datagrid_attribute :order
+ datagrid_attribute :reverse
+
+
+ end
+ base.send :include, InstanceMethods
+ end # self.included
+
+ module ClassMethods
+
+ def columns
+ @columns ||= []
+ end
+
+ def column(name, options = {}, &block)
+ block ||= lambda do
+ self.send(name)
+ end
+ self.columns << Datagrid::Columns::Column.new(self, name, options, &block)
+ end
+
+
+ end # ClassMethods
+
+ module InstanceMethods
+
+ def header
+ self.class.columns.map(&:header)
+ end
+
+ def row_for(asset)
+ self.class.columns.map do |column|
+ column.value(asset)
+ end
+ end
+
+ def hash_for(asset)
+ result = {}
+ self.class.columns.each do |column|
+ result[column.name] = column.value(asset)
+ end
+ result
+ end
+
+ def data
+ self.assets.map do |asset|
+ self.row_for(asset)
+ end
+ end
+
+ def data_hash
+ self.assets.map do |asset|
+ hash_for(asset)
+ end
+ end
+
+ def assets
+ result = super
+ if self.order
+ column = column_by_name(self.order)
+ raise Datagrid::OrderUnsupported, "Can not sort #{self.inspect} by #{name.inspect}" unless column
+ result = result.order(self.reverse ? column.desc_order : column.order)
+ end
+ result
+ end
+
+ def to_csv(options = {})
+ require "fastercsv"
+ FasterCSV.generate(
+ {:headers => self.header, :write_headers => true}.merge(options)
+ ) do |csv|
+ self.data.each do |row|
+ csv << row
+ end
+ end
+ end
+
+ def columns
+ self.class.columns
+ end
+
+ def column_by_name(name)
+ self.columns.find do |col|
+ col.name.to_sym == name.to_sym
+ end
+ end
+
+ end # InstanceMethods
+
+ end
+end
46 lib/datagrid/columns/column.rb
@@ -0,0 +1,46 @@
+
+class Datagrid::Columns::Column
+
+ attr_accessor :grid, :options, :block, :name
+
+ def initialize(grid, name, options = {}, &block)
+ self.grid = grid
+ self.name = name
+ self.options = options
+ self.block = block
+ end
+
+ def value(object)
+ value_for(object)
+ end
+
+ def value_for(object)
+ object.instance_eval(&self.block)
+ end
+
+ def format
+ self.options[:format]
+ end
+
+ def label
+ self.options[:label]
+ end
+
+ def header
+ self.options[:header] ||
+ I18n.translate(self.name, :scope => "reports.#{self.grid}.columns", :default => self.name.to_s.humanize )
+ end
+
+ def order
+ if options.has_key?(:order)
+ self.options[:order]
+ else
+ grid.scope.column_names.include?(name.to_s) ? [grid.scope.table_name, name].join(".") : nil
+ end
+ end
+
+ def desc_order
+ self.options[:desc_order] || (order ? order.to_s + " DESC" : nil)
+ end
+
+end
99 lib/datagrid/core.rb
@@ -0,0 +1,99 @@
+module Datagrid
+ module Core
+
+ def self.included(base)
+ base.extend ClassMethods
+ base.class_eval do
+
+ end
+ base.send :include, InstanceMethods
+ end # self.included
+
+ module ClassMethods
+
+ def datagrid_attribute(name, &block)
+ unless datagrid_attributes.include?(name)
+ block ||= lambda do |value|
+ value
+ end
+ datagrid_attributes << name
+ define_method name do
+ instance_variable_get("@#{name}")
+ end
+
+ define_method :"#{name}=" do |value|
+ instance_variable_set("@#{name}", block.call(value))
+ end
+ end
+ end
+
+ def datagrid_attributes
+ @datagrid_attributes ||= []
+ end
+
+ def scope(&block)
+ if block
+ @scope = block
+ else
+ raise(Datagrid::ConfigurationError, "Scope not defined") unless @scope
+ @scope.call
+ end
+ end
+
+ def param_name
+ self.to_s.underscore.split('/').last
+ end
+
+ end # ClassMethods
+
+ module InstanceMethods
+
+ def initialize(attributes = nil)
+ super()
+
+ if attributes
+ self.attributes = attributes
+ end
+ end
+
+ def attributes
+ result = {}
+ self.class.datagrid_attributes.each do |name|
+ result[name] = self[name]
+ end
+ result
+ end
+
+ def [](attribute)
+ self.send(attribute)
+ end
+
+ def []=(attribute, value)
+ self.send(:"#{attribute}=", value)
+ end
+
+ def assets
+ scope.scoped({})
+ end
+
+ def attributes=(attributes)
+ attributes.each do |name, value|
+ self[name] = value
+ end
+ end
+
+ def paginate(*args, &block)
+ self.assets.paginate(*args, &block)
+ end
+
+ def scope
+ self.class.scope
+ end
+
+ def param_name
+ self.class.param_name
+ end
+
+ end # InstanceMethods
+ end
+end
150 lib/datagrid/filters.rb
@@ -0,0 +1,150 @@
+module Datagrid
+ module Filters
+
+ require "datagrid/filters/base_filter"
+ require "datagrid/filters/enum_filter"
+ require "datagrid/filters/boolean_enum_filter"
+ require "datagrid/filters/boolean_filter"
+ require "datagrid/filters/date_filter"
+ require "datagrid/filters/default_filter"
+ require "datagrid/filters/filter_eval"
+ require "datagrid/filters/integer_filter"
+ require "datagrid/filters/composite_filters"
+
+ FILTER_TYPES = {
+ :date => Filters::DateFilter,
+ :string => Filters::DefaultFilter,
+ :default => Filters::DefaultFilter,
+ :eboolean => Filters::BooleanEnumFilter ,
+ :boolean => Filters::BooleanFilter ,
+ :integer => Filters::IntegerFilter,
+ :enum => Filters::EnumFilter,
+ }
+
+ def self.included(base)
+ base.extend ClassMethods
+ base.class_eval do
+
+ include Datagrid::Core
+ include Datagrid::Filters::CompositeFilters
+
+ end
+ base.send :include, InstanceMethods
+ end # self.included
+
+ module ClassMethods
+
+ def filters
+ @filters ||= []
+ end
+
+ def filter_by_name(attribute)
+ self.filters.find do |filter|
+ filter.name.to_sym == attribute.to_sym
+ end
+ end
+
+
+ # Defines the accessible attribute that is used to filter
+ # scope by the specified value with specified code.
+ #
+ # Example:
+ #
+ # class UserGrid
+ # include Datagrid
+ #
+ # filter(:name)
+ # filter(:posts_count, :integer) do |value|
+ # self.where(["posts_count >= ?", value])
+ # end
+ #
+ # scope do
+ # User.order("users.created_at desc")
+ # end
+ # end
+ #
+ # Each filter becomes grid atttribute.
+ # In order to create grid that display all users with name 'John' that have more than zero posts:
+ #
+ # grid = UserGrid.new(:posts_count => 1, :name => "John")
+ # grid.assets # SELECT * FROM users WHERE users.posts_count > 1 AND name = 'John'
+ #
+ # Important! Take care about non-breaking the filter chain and force objects loading in filter.
+ # The filter block should always return a <tt>ActiveRecord::Scope</tt> rather than <tt>Array</tt>
+ #
+ # = Default filter block
+ #
+ # If no block given filter is generated automatically as simple select by filter name from scope.
+ #
+ # = Filter types
+ #
+ # Filter does types conversion automatically.
+ # The following filter types are supported:
+ #
+ # * <tt>:string</tt> (default) - converts value to string
+ # * <tt>:date</tt> - converts value to date using date parser
+ # * <tt>:enum</tt> - designed to be collection select. Additional options for easy form generation:
+ # * <tt>:select</tt> (required) - collection of values to match agains.
+ # * <tt>:multiple</tt> - if true multiple values can be assigned to this filter. Default: false.
+ # * <tt>:eboolean</tt> - subtype of enum filter that provides select of "Yes", "No" and "Any". Could be useful.
+ # * <tt>:integer</tt> - converts given value to integer.
+ #
+ #
+ def filter(attribute, type = :string, options = {}, &block)
+
+ klass = type.is_a?(Class) ? type : FILTER_TYPES[type]
+ raise ConfigurationError, "filter class not found" unless klass
+
+ block ||= default_filter(attribute)
+
+ filter = klass.new(self, attribute, options, &block)
+ self.filters << filter
+
+ datagrid_attribute(attribute) do |value|
+ filter.format(value)
+ end
+
+ end
+
+ protected
+ def default_filter(attribute)
+ if self.scope.column_names.include?(attribute.to_s)
+ lambda do |value|
+ self.scoped(:conditions => {attribute => value})
+ end
+ else
+ raise ConfigurationError, "Not able to generate default filter. No column '#{attribute}' in #{self.scope.table_name}."
+ end
+ end
+
+ end # ClassMethods
+
+ module InstanceMethods
+
+ def initialize(*args, &block)
+ self.filters.each do |filter|
+ self[filter.name] = filter.default
+ end
+ super(*args, &block)
+ end
+
+ def assets
+ result = super
+ self.class.filters.each do |filter|
+ result = filter.apply(result, filter_value(filter))
+ end
+ result
+ end
+
+ def filters
+ self.class.filters
+ end
+
+ def filter_value(filter)
+ self[filter.name]
+ end
+
+ end # InstanceMethods
+
+ end
+end
33 lib/datagrid/filters/base_filter.rb
@@ -0,0 +1,33 @@
+require "datagrid/filters/filter_eval"
+
+class Datagrid::Filters::BaseFilter
+
+ attr_accessor :grid, :options, :block, :name
+
+ def initialize(grid, name, options = {}, &block)
+ self.grid = grid
+ self.name = name
+ self.options = options
+ self.block = block
+ end
+
+ def apply(scope, value)
+ return scope if value.nil? && !options[:allow_nil]
+ return scope if value.blank? && !options[:allow_blank]
+ ::Datagrid::Filters::FilterEval.new(self, scope, value).run
+ end
+
+ def format(value)
+ raise NotImplementedError, "#format(value) suppose to be overwritten"
+ end
+
+ def header
+ I18n.translate(self.name, :scope => "datagrid.#{grid.class.to_s.underscore.split("/").last}.filters", :default => self.name.to_s.humanize)
+ end
+
+ def default
+ self.options[:default]
+ end
+
+end
+
21 lib/datagrid/filters/boolean_enum_filter.rb
@@ -0,0 +1,21 @@
+class Datagrid::Filters::BooleanEnumFilter < Datagrid::Filters::EnumFilter
+
+ YES = "YES"
+ NO = "NO"
+ VALUES = {YES => true, NO => false}
+
+ def initialize(report, attribute, options = {}, &block)
+ options[:allow_blank] = true unless options.has_key?(:allow_blank)
+ options[:select] = VALUES.keys
+ super(report, attribute, options, &block)
+ end
+
+ def apply(scope, value)
+ super(scope, to_boolean(value))
+ end
+
+ def to_boolean(value)
+ VALUES[value]
+ end
+
+end
7 lib/datagrid/filters/boolean_filter.rb
@@ -0,0 +1,7 @@
+class Datagrid::Filters::BooleanFilter < Datagrid::Filters::BaseFilter
+
+ def format(value)
+ [true, 1, "1", "true", "yes", "on"].include?(value)
+ end
+
+end
41 lib/datagrid/filters/composite_filters.rb
@@ -0,0 +1,41 @@
+module Datagrid
+ module Filters
+ module CompositeFilters
+
+ def self.included(base)
+ base.extend ClassMethods
+ base.class_eval do
+
+ end
+ base.send :include, InstanceMethods
+ end # self.included
+
+ module ClassMethods
+
+
+ def date_range_filters(field, from_name = :"from_#{field}", to_name = :"to_#{field}")
+ filter(from_name, :date) do |date|
+ self.from_date(date, field)
+ end
+ filter(to_name, :date) do |date|
+ self.to_date(date, field)
+ end
+ end
+
+ def integer_range_filters(field, from_name = :"from_#{field}", to_name = :"to_#{field}")
+ filter(from_name, :integer) do |value|
+ self.scoped(:conditions => "#{field} >= #{value}")
+ end
+ filter(to_name, :integer) do |value|
+ self.scoped(:conditions => "#{field} <= #{value}")
+ end
+ end
+ end # ClassMethods
+
+ module InstanceMethods
+
+ end # InstanceMethods
+
+ end
+ end
+end
12 lib/datagrid/filters/date_filter.rb
@@ -0,0 +1,12 @@
+class Datagrid::Filters::DateFilter < Datagrid::Filters::BaseFilter
+ #TODO: more smart date normalizer
+ def format(value)
+ return nil if value.blank?
+ return value.to_date if value.respond_to?(:to_date)
+ return value unless value.is_a?(String)
+ Date.parse(value)
+ rescue ArgumentError
+ nil
+ end
+end
+
5 lib/datagrid/filters/default_filter.rb
@@ -0,0 +1,5 @@
+class Datagrid::Filters::DefaultFilter < Datagrid::Filters::BaseFilter
+ def format(value)
+ value
+ end
+end
32 lib/datagrid/filters/enum_filter.rb
@@ -0,0 +1,32 @@
+class Datagrid::Filters::EnumFilter < Datagrid::Filters::BaseFilter
+
+ def initialize(*args)
+ super(*args)
+ raise Datagrid::ConfigurationError, ":select option not specified" unless select
+ end
+ def format(value)
+ values = Array.new([*value])
+ values.reject do |value|
+ #TODO: really impelement #strict option
+ self.strict && !select.include?(value)
+ end
+ self.multiple ? values : values.first
+ end
+
+ def select
+ self.options[:select]
+ end
+
+
+ def include_blank
+ self.options.has_key?(:include_blank) ? options[:include_blank] : true
+ end
+
+ def strict
+ self.options[:strict]
+ end
+
+ def multiple
+ self.options[:multiple]
+ end
+end
25 lib/datagrid/filters/filter_eval.rb
@@ -0,0 +1,25 @@
+# ActiveRecord is a little brain fuck.
+# We can not call instance_eval on ActiveRecord::Relation class
+# because it will automatically convert it to an array because #instance_eval
+# is not included in the method list that do not cause force result loading
+# That is why we need thi helper class
+class Datagrid::Filters::FilterEval
+
+ def initialize(filter, scope, value)
+ @filter = filter
+ @scope = scope
+ @value = value
+ end
+
+ def run
+ instance_exec @value, &(@filter.block)
+ end
+
+ def method_missing(meth, *args, &blk)
+ if @scope.respond_to?(meth)
+ @scope.send(meth, *args, &blk)
+ else
+ super(meth, *args, &blk)
+ end
+ end
+end
7 lib/datagrid/filters/integer_filter.rb
@@ -0,0 +1,7 @@
+class Datagrid::Filters::IntegerFilter < Datagrid::Filters::BaseFilter
+ def format(value)
+ return nil if value.blank?
+ value.to_i
+ end
+end
+
56 lib/datagrid/form_builder.rb
@@ -0,0 +1,56 @@
+require "action_view"
+
+module Datagrid
+ module FormBuilder
+
+ def datagrid_filter(filter_or_attribute, options = {})
+ filter = get_filter(filter_or_attribute)
+ options[:class] ||= ""
+ options[:class] += " " unless options[:class].blank?
+ options[:class] += "#{filter.name} #{datagrid_filter_class(filter.class)}"
+ self.send(:"datagrid_#{filter.class.to_s.underscore.split('/').last}", filter, options)
+ end
+
+ protected
+ def datagrid_boolean_enum_filter(attribute_or_filter, options = {})
+ datagrid_enum_filter(attribute_or_filter, options)
+ end
+
+ def datagrid_boolean_filter(attribute_or_filter, options = {})
+ check_box(get_attribute(attribute_or_filter), options)
+ end
+
+ def datagrid_date_filter(attribute_or_filter, options = {})
+ attribute = get_attribute(attribute_or_filter)
+ text_field(attribute, options)
+ end
+
+ def datagrid_default_filter(attribute_or_filter, options = {})
+ text_field get_attribute(attribute_or_filter), options
+ end
+
+ def datagrid_enum_filter(attribute_or_filter, options = {})
+ filter = get_filter(attribute_or_filter)
+ select filter.name, filter.select || [], {:include_blank => filter.include_blank}, {:multiple => filter.multiple}.merge(options)
+ end
+
+ def datagrid_integer_filter(attribute_or_filter, options = {})
+ text_field get_attribute(attribute_or_filter), options
+ end
+
+ def get_attribute(attribute_or_filter)
+ attribute_or_filter.is_a?(Symbol) ? attribute_or_filter : attribute_or_filter.name
+ end
+
+ def get_filter(attribute_or_filter)
+ attribute_or_filter.is_a?(Symbol) ? object.class.filter_by_name(attribute_or_filter) : attribute_or_filter
+ end
+
+ def datagrid_filter_class(klass)
+ klass.to_s.split("::").last.underscore
+ end
+ end
+end
+
+ActionView::Helpers::FormBuilder.send(:include, Datagrid::FormBuilder)
+
80 lib/datagrid/helper.rb
@@ -0,0 +1,80 @@
+require "action_view"
+
+module Datagrid
+ module Helper
+
+ def datagrid_format_value(column, asset)
+ value = column.value(asset)
+ if column.options[:url]
+ link_to(value, column.options[:url].call(asset))
+ else
+ case column.format
+ when :url
+ link_to(column.label ? asset.send(column.label) : I18n.t("datagrid.table.url_label", :default => "URL"), value)
+ else
+ value
+ end
+ end
+ end
+
+ def datagrid_table(report, *args)
+ options = args.extract_options!
+ html = options[:html] || {}
+ html[:class] ||= "datagrid"
+ paginate = options[:paginate] || {}
+ paginate[:page] ||= params[:page]
+ assets = report.assets.paginate(paginate)
+ content_tag(:table, html) do
+ table = content_tag(:tr, datagrid_header(report, options))
+ table << datagrid_rows(report.columns, assets, options)
+ table
+ end
+ end
+
+ protected
+
+ def datagrid_header(grid, options)
+ header = empty_string
+ grid.columns.each do |column|
+ data = column.header.html_safe
+ if column.order
+ data << datagrid_order_for(grid, column)
+ end
+ header << content_tag(:th, data)
+ end
+ header
+ end
+
+ def datagrid_rows(columns, assets, options)
+ rows = empty_string
+ assets.each do |asset|
+ rows << content_tag(:tr, :class => cycle("odd", "even")) do
+ html = empty_string
+ columns.each do |column|
+ html << content_tag(:td, datagrid_format_value(column, asset))
+ end
+ html
+ end
+
+ end
+ rows
+ end
+
+ def datagrid_order_for(grid, column)
+ content_tag(:div, :class => "order") do
+ link_to(
+ I18n.t("datagrid.table.order.asc", :default => "ASC"), url_for(grid.param_name => grid.attributes.merge(:order => column.name))
+ ) + " " +
+ link_to(I18n.t("datagrid.table.order.desc", :default => "DESC"), url_for(grid.param_name => grid.attributes.merge(:order => column.name, :reverse => true )))
+ end
+ end
+
+ def empty_string
+ res = ""
+ res.respond_to?(:html_safe) ? res.html_safe : res
+ end
+ end
+
+ ::ActionView::Base.send(:include, ::Datagrid::Helper)
+
+end
68 lib/datagrid/rspec.rb
@@ -0,0 +1,68 @@
+shared_examples_for "Datagrid" do
+ describe "as Datagrid" do
+
+ it "should have at least one entry if assets" do
+ subject.assets.should_not be_empty
+ end
+
+ its(:data) {should_not be_empty}
+
+ described_class.columns.each do |column|
+ describe "column ##{column.name}" do
+
+ it "should has value in #data_hash" do
+ subject.data_hash.first.should have_key(column.name)
+ end
+
+ it "should support order" do
+ subject.order = column.name
+ subject.assets.first.should_not be_nil
+ end
+
+ it "should support reverse order" do
+ subject.reverse = true
+ subject.assets.first.should_not be_nil
+ end
+ end
+
+ end
+
+ described_class.filters.each do |filter|
+ describe "filter ##{filter.name}" do
+
+ let(:filter_value) do
+
+ case Datagrid::Filters::FILTER_TYPES.invert[filter.class]
+ when :default, :string
+ "text"
+ when :date
+ 1.day.ago
+ when :eboolean
+ Datagrid::Filters::BooleanEnumFilter::YES
+ when :boolean
+ true
+ when :integer
+ 1
+ when :enum
+ select = filter.select
+ select = select.call(subject) if select.respond_to?(:call)
+ select.first.try(:last)
+ else
+ raise "unknown filter type: #{filter.class}"
+ end.to_s
+ end
+
+ before(:each) do
+ subject.attributes = {filter.name => filter_value}
+ subject.send(filter.name).should_not be_nil
+ end
+
+ it "should be supported" do
+ subject.assets.should_not be_nil
+ #TODO: better matcher.
+ end
+ end
+ end
+
+ end
+end
68 spec/datagrid/form_builder_spec.rb
@@ -0,0 +1,68 @@
+require 'spec_helper'
+
+
+class MyFormBuilder
+ include Datagrid::FormBuilder
+end
+
+class MyTemplate
+ include ActionView::Helpers::FormHelper
+end
+
+
+describe Datagrid::FormBuilder do
+
+ let(:template) { ActionView::Base.new}
+ let(:grid) { SimpleReport.new }
+ let(:view) { ActionView::Helpers::FormBuilder.new(:report, grid, template, {}, Proc.new {|f| })}
+ subject { view }
+
+
+ describe ".datagrid_filter" do
+
+ subject { view.datagrid_filter(_filter)}
+ context "with default filter type" do
+ let(:_filter) { :name }
+ it { should equal_to_dom(
+ '<input class="name default_filter" id="report_name" name="report[name]" size="30" type="text"/>'
+ )}
+ end
+ context "with integer filter type" do
+ let(:_filter) { :group_id }
+ it { should equal_to_dom(
+ '<input class="group_id integer_filter" id="report_group_id" name="report[group_id]" size="30" type="text"/>'
+ )}
+ end
+ context "with enum filter type" do
+ let(:_filter) { :category }
+ it { should equal_to_dom(
+ '<select class="category enum_filter" id="report_category" name="report[category][]"><option value=""></option>
+ <option value="first">first</option>
+ <option value="second">second</option></select>'
+ )}
+ context "when first option is selected" do
+ before(:each) do
+ grid.category = "first"
+ end
+ it { should equal_to_dom(
+ '<select class="category enum_filter" id="report_category" name="report[category][]"><option value=""></option>
+ <option value="first" selected="true">first</option>
+ <option value="second">second</option></select>'
+ )}
+ end
+ end
+
+ context "with eboolean filter type" do
+ let(:_filter) { :disabled }
+ it { should equal_to_dom(
+ '<select class="disabled boolean_enum_filter" id="report_disabled" name="report[disabled][]"><option value=""></option>
+ <option value="NO">NO</option>
+ <option value="YES">YES</option></select>'
+ )}
+ end
+ end
+end
+
+
+
+
46 spec/datagrid/helper_spec.rb
@@ -0,0 +1,46 @@
+require 'spec_helper'
+require "will_paginate"
+require "active_support/core_ext/hash"
+require "active_support/core_ext/object"
+
+describe Datagrid::Helper do
+ subject {ActionView::Base.new}
+
+ before(:each) do
+ subject.stub!(:params).and_return({})
+ subject.stub(:url_for) do |options|
+ options.to_param
+ end
+
+ end
+
+ let(:group) { Group.create!(:name => "Pop") }
+ let!(:entry) { Entry.create!(
+ :group => group, :name => "Star", :disabled => false, :confirmed => false, :category => "first"
+ ) }
+ let(:grid) { SimpleReport.new }
+
+ describe ".report_table" do
+ before(:each) do
+ subject.stub!(:datagrid_order_for).and_return(subject.content_tag(:div, "", :class => "order"))
+ end
+ it "should return data table html" do
+ subject.datagrid_table(grid).should equal_to_dom(
+'<table class="datagrid">
+<tr>
+<th>Group<div class="order"></div>
+</th>
+<th>Name<div class="order"></div>
+</th>
+</tr>
+
+<tr class="odd">
+<td>Pop</td>
+<td>Star</td>
+</tr>
+</table>')
+ end
+ end
+
+
+end
56 spec/datagrid_spec.rb
@@ -0,0 +1,56 @@
+require 'spec_helper'
+
+
+describe SimpleReport do
+
+ it_should_behave_like 'Datagrid'
+
+ let(:group) { Group.create!(:name => "Pop") }
+
+ subject do
+ SimpleReport.new(
+ :group_id => group.id,
+ :name => "Star",
+ :category => "first",
+ :disabled => false,
+ :confirmed => false
+ )
+ end
+
+ let!(:entry) { Entry.create!(
+ :group => group, :name => "Star", :disabled => false, :confirmed => false, :category => "first"
+ ) }
+
+ its(:assets) { should include(entry) }
+
+ describe ".attributes" do
+ it "should return report attributes" do
+ (subject.filters.map(&:name) + [:order, :reverse]).each do |attribute|
+ subject.attributes.should have_key(attribute)
+ end
+ end
+
+ end
+
+ describe ".scope" do
+ it "should return defined scope of objects" do
+ subject.scope.should respond_to(:table_name)
+ end
+
+
+ context "when not defined on class level" do
+ before(:each) do
+ SimpleReport.instance_variable_set("@scope", nil)
+ end
+
+ it "should raise ConfigurationError" do
+ lambda {
+ subject.scope
+ }.should raise_error(Datagrid::ConfigurationError)
+
+ end
+
+ end
+ end
+
+end
39 spec/spec_helper.rb
@@ -0,0 +1,39 @@
+require 'rubygems'
+require 'bundler'
+begin
+ Bundler.setup(:default, :development)
+rescue Bundler::BundlerError => e
+ $stderr.puts e.message
+ $stderr.puts "Run `bundle install` to install missing gems"
+ exit e.status_code
+end
+$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
+$LOAD_PATH.unshift(File.dirname(__FILE__))
+
+require 'rspec'
+require "active_record"
+require "will_paginate"
+require 'datagrid'
+require "datagrid/rspec"
+require 'ruby-debug'
+
+
+RSpec.configure do |config|
+
+
+ config.after(:each) do
+ #TODO better database truncation
+ Group.delete_all
+ Entry.delete_all
+
+ end
+
+
+end
+
+
+
+# Requires supporting files with custom matchers and macros, etc,
+# in ./support/ and its subdirectories.
+Dir["#{File.dirname(__FILE__)}/support/schema.rb"].each {|f| require f}
+Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
42 spec/support/equal_to_dom.rb
@@ -0,0 +1,42 @@
+require "nokogiri"
+
+def equal_to_dom(text)
+ EqualToDom.new(text)
+end
+
+
+def include_dom(text)
+ IncludeDom.new(text)
+end
+
+class IncludeDom
+ def initialize(expectation)
+ @expectation = Nokogiri::HTML::DocumentFragment.parse(expectation).to_s
+ end
+
+ def matches?(text)
+ @matcher = Nokogiri::HTML::DocumentFragment.parse(text).to_s
+ @matcher.include?(@expectation)
+ end
+
+ def failure_message
+ "Expected dom #{@matcher} to include #{@expectation}, but it wasn't"
+ end
+end
+
+
+class EqualToDom
+
+ def initialize(expectation)
+ @expectation = Nokogiri::HTML::DocumentFragment.parse(expectation).to_s
+ end
+
+ def matches?(text)
+ @matcher = Nokogiri::HTML::DocumentFragment.parse(text).to_s
+ @matcher == @expectation
+ end
+
+ def failure_message
+ "Expected dom #{@matcher} to match #{@expectation}, but it wasn't"
+ end
+end
35 spec/support/schema.rb
@@ -0,0 +1,35 @@
+require "logger"
+
+ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
+ActiveRecord::Base.configurations = true
+
+File.open('spec.log', "w").close
+ActiveRecord::Base.logger = Logger.new('spec.log')
+
+
+
+WillPaginate.enable
+
+ActiveRecord::Schema.verbose = false
+ActiveRecord::Schema.define(:version => 1) do
+
+ create_table :entries do |t|
+ t.integer :group_id
+ t.string :name
+ t.string :category
+ t.boolean :disabled, :null => false, :default => nil
+ t.boolean :confirmed, :null => false, :default => nil
+ t.timestamps
+ end
+
+ create_table :groups do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ class ::Entry < ActiveRecord::Base
+ belongs_to :group
+ end
+ class ::Group < ActiveRecord::Base
+ end
+end
28 spec/support/simple_report.rb
@@ -0,0 +1,28 @@
+class SimpleReport
+
+ include Datagrid
+
+
+ scope do
+ ::Entry.includes(:group).order(:created_at)
+ end
+
+ filter(:group_id, :integer)
+ filter(:category, :enum, :select => ["first", "second"])
+ filter(:disabled, :eboolean)
+ filter(:confirmed, :boolean)
+ filter(:name) do |value|
+ self.scoped(:conditions => {:name => value})
+ end
+
+ column(:group, :order => "groups.name") do |model|
+ group.name
+ end
+
+ column(:name)
+
+ def param_name
+ :report
+ end
+
+end

0 comments on commit 5e3f5b7

Please sign in to comment.
Something went wrong with that request. Please try again.