jqgrid_for_rails 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,2 @@
1
+ test/*.log
2
+ test/*.db
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010 [name of plugin creator]
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,116 @@
1
+ == JqgridForRails
2
+
3
+ This is a simple plug-in to create JqGrid(http://www.trirand.com/blog) javascript code easily and cleaner inside rails views.
4
+
5
+ == Example
6
+
7
+ There is an example application at:
8
+
9
+ https://github.com/Juanmcuello/jqgrid_for_rails_example
10
+
11
+
12
+ == Installation
13
+
14
+ To install it as a plugin just:
15
+
16
+ $ rails plugin install git@github.com:Juanmcuello/jqgrid_for_rails.git
17
+
18
+
19
+ == Views
20
+
21
+ To generate the grid, you can first create a method in a helper and then call the +jqgrid+ method to generate the java script code. For example, if you have an invoices_helper.rb file, you can define a method there:
22
+
23
+ module InvoicesHelper
24
+
25
+ include JqgridsHelper
26
+
27
+ def invoices_jqgrid
28
+
29
+ options = {:html_tags => true}
30
+ grid_options = {
31
+ :url => '/invoices',
32
+ :datatype => 'json',
33
+ :mtype => 'GET',
34
+ :colNames => ['Inv No','Date'],
35
+ :colModel => [
36
+ { :name => 'invid', :index => 'invid', :width => 55 },
37
+ { :name => 'invdate', :index => 'invdate', :width => 90 },
38
+ ],
39
+ :pager => '#invoices_pager',
40
+ :rowNum => 10,
41
+ :rowList => [10, 20, 30],
42
+ :caption => 'My first grid',
43
+ :onSelectRow => "function() { alert('Row selected!');}".to_json_var
44
+ }
45
+
46
+ jqgrid 'invoices_list', options, grid_options
47
+ end
48
+ end
49
+
50
+ Now you can use the helper in the view:
51
+
52
+ <%= raw(invoices_jqgrid) %>
53
+
54
+ Or, if you are using Rails 2.3.x :
55
+
56
+ <%= invoices_jqgrid %>
57
+
58
+ This will result in something like:
59
+
60
+ <table id="invoices_list"></table>
61
+ <div id="invoices_pager"></div>
62
+ <script>
63
+ jQuery("#invoices_list").jqGrid({
64
+ "url": "/invoices",
65
+ "datatype": "json",
66
+ "mtype": "GET",
67
+ "colNames": ["Inv No","Date"],
68
+ "colModel": [
69
+ {"name":"invid", "index":"invid", "width":55},
70
+ {"name":"invdate", "index":"invdate", "width":90}],
71
+ "pager": "#invoices_pager",
72
+ "rowNum": 10,
73
+ "rowList": [10,20,30],
74
+ "caption": "My first grid",
75
+ "onSelectRow": function() { alert('Row selected!');}});
76
+
77
+ jQuery("#invoices_list").jqGrid("navGrid", "#invoices_pager", {});
78
+
79
+ </script
80
+
81
+ Note: resulting code was indented for clarification.
82
+
83
+ You can do it better using +content_for+ :
84
+
85
+ At the views:
86
+
87
+ <% content_for :head do %>
88
+ <%= invoices_jqgrid %>
89
+ <% end %>
90
+
91
+
92
+ Don't forget to include the jquery and jqgrid javascript and stylesheet files!
93
+
94
+ == Controllers
95
+
96
+ You can use the +json_for_jqgrid+ method at the controllers to generate the json response for the grid. It receives the records found by the +paginate+ method offered by will_paginate[https://github.com/mislav/will_paginate].
97
+
98
+ def index
99
+
100
+ @columns = ['invid', 'invdate']
101
+
102
+ @invoices = Invoice.paginate(:page => params[:page], :per_page => params[:rows] )
103
+
104
+ if request.xhr?
105
+ render :json => json_for_jqgrid(@invoices, @columns, {:page => params[:page]})
106
+ end
107
+ end
108
+
109
+
110
+ == Maintainers
111
+
112
+ * Juan Manuel Cuello (http://github.com/Juanmcuello)
113
+
114
+ == License
115
+
116
+ Copyright (c) 2010 Juan M. Cuello, released under the MIT license
data/Rakefile ADDED
@@ -0,0 +1,24 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+
5
+ desc 'Default: run unit tests.'
6
+ task :default => :test
7
+
8
+ desc 'Test the jqgrid_for_rails plugin.'
9
+ Rake::TestTask.new(:test) do |t|
10
+ t.libs << '.'
11
+ t.libs << 'lib'
12
+ t.libs << 'test'
13
+ t.pattern = 'test/**/*_test.rb'
14
+ t.verbose = true
15
+ end
16
+
17
+ desc 'Generate documentation for the jqgrid_for_rails plugin.'
18
+ Rake::RDocTask.new(:rdoc) do |rdoc|
19
+ rdoc.rdoc_dir = 'rdoc'
20
+ rdoc.title = 'JqgridForRails'
21
+ rdoc.options << '--line-numbers' << '--inline-source'
22
+ rdoc.rdoc_files.include('README')
23
+ rdoc.rdoc_files.include('lib/**/*.rb')
24
+ end
data/install.rb ADDED
@@ -0,0 +1 @@
1
+ # Install hook code here
@@ -0,0 +1,101 @@
1
+ module JqgridsHelper
2
+
3
+ # Generates the jqGrid javascript code. Also html tags for the table and pager can be generated.
4
+ # The javascript code is enclosed between the <script> tags.
5
+ #
6
+ # The +grid_id+ parameter should be the id of the html table tag that will contain the grid.
7
+ # If [:html_tags] is +true+, the grid_id will be used when creating the <table> tags.
8
+ #
9
+ # === Options
10
+ #
11
+ # [:html_tags]
12
+ # If true, <table> tag for the grid, and <div> tag for the table will be generated as well.
13
+ #
14
+ # [:on_document_ready]
15
+ # If true, all the javascript code will be enclosed inside a +jQuery(document).ready+ function
16
+ #
17
+ # === Grid Options
18
+ #
19
+ # This hash can contain any option accepted by the jqGrid. The has will encoded to json to create
20
+ # the javascript code for the grid.
21
+ #
22
+ # See http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
23
+ #
24
+ # For options that represents javascript functions, the value should be converted to a json_var
25
+ # using the +to_json_var+ method.
26
+ #
27
+ # For example:
28
+ # :onLoadComplete => "function() { alert('This is a function!');}".to_json_var
29
+ #
30
+ # === Nav Options
31
+ #
32
+ # This hash can contain any option accepted by the nav options of jqGrid.
33
+ #
34
+ # === Example
35
+ #
36
+ # options = {:on_document_ready => true, :html_tags => false}
37
+ #
38
+ # grid_options = {
39
+ # :url => '/invoices',
40
+ # :datatype => 'json',
41
+ # :mtype => 'GET',
42
+ # :colNames => ['Inv No','Date', 'Amount','Tax','Total','Notes'],
43
+ # :colModel => [
44
+ # { :name => 'invid', :index => 'invid', :width => 55 },
45
+ # { :name => 'invdate', :index => 'invdate', :width => 90 },
46
+ # { :name => 'amount', :index => 'amount', :width => 80, :align => 'right' },
47
+ # { :name => 'tax', :index => 'tax', :width => 80, :align => 'right' },
48
+ # { :name => 'total', :index => 'total', :width => 80, :align => 'right' },
49
+ # { :name => 'note', :index => 'note', :width => 150, :sortable => false }
50
+ # ],
51
+ # :pager => '#invoices_pager',
52
+ # :rowNum => 10,
53
+ # :rowList => [10, 20, 30],
54
+ # :sortname => 'invid',
55
+ # :sortorder => 'desc',
56
+ # :viewrecords => true,
57
+ # :caption => 'My first grid',
58
+ # :onSelectRow => "function() { alert('Row selected!');}".to_json_var
59
+ # }
60
+ #
61
+ # jqgrid 'invoices_list', options, grid_options
62
+ #
63
+ def jqgrid grid_id, options = {}, grid_options = {}, nav_options = {}
64
+
65
+ html_output = []
66
+
67
+ # Table
68
+ html_output << content_tag(:table, nil, :id => grid_id) if options[:html_tags]
69
+ js_output = "jQuery(\"##{grid_id}\").jqGrid(#{grid_options.to_json});"
70
+
71
+ # Pager
72
+ if grid_options[:pager]
73
+
74
+ pager_id = id_from_pager_option(grid_options[:pager])
75
+
76
+ html_output << content_tag(:div, nil, :id => pager_id) if options[:html_tags]
77
+
78
+ if nav_options
79
+ js_output << "jQuery(\"##{grid_id}\").jqGrid(\"navGrid\", \"##{pager_id}\", #{nav_options.to_json});"
80
+ end
81
+ end
82
+
83
+ wrap_with_document_ready! js_output if options[:on_document_ready]
84
+
85
+ html_output << "<script>" << js_output << "</script>"
86
+
87
+ html_output.join("\n")
88
+ end
89
+
90
+ private
91
+
92
+ def wrap_with_document_ready! str
93
+ str.replace("jQuery(document).ready(function() {#{str}});")
94
+ end
95
+
96
+ def id_from_pager_option pager_option
97
+ pager_option.match(/#\w+/).to_s[1..-1]
98
+ end
99
+
100
+ end
101
+
@@ -0,0 +1,57 @@
1
+ module JqgridForRails
2
+ module Controllers
3
+ # Those helpers are convenience methods added to ApplicationController.
4
+ module Helpers
5
+
6
+ # Returns a json string ready to be send to a jqgrid component.
7
+ #
8
+ # +records+ should be the result of an active record query through
9
+ # the +paginate+ method offered by will_paginate.
10
+ #
11
+ # +columns+ is an array with the name of the fields in the order they
12
+ # should be returned.
13
+ #
14
+ # === Options
15
+ #
16
+ # [:id_column]
17
+ # Says which is the column that should be used as the row id
18
+ #
19
+ # :page]
20
+ # Says the page number
21
+ #
22
+ def json_for_jqgrid records, columns = nil, options = {}
23
+
24
+ return if records.empty?
25
+
26
+ columns ||= records.first.attributes.keys
27
+
28
+ options[:id_column] ||= columns.first
29
+ options[:page] ||= 1
30
+
31
+ { :page => options[:page],
32
+ :total => records.total_pages,
33
+ :records => records.total_entries,
34
+ :rows => records.map do |r| {
35
+ :id => r.attributes[options[:id_column]],
36
+ :cell => r.attributes.values_at(*columns)}
37
+ end
38
+ }.to_json
39
+ end
40
+
41
+ # Returns the 'order by' string created using the params received from the jqgrid.
42
+ #
43
+ # === Example
44
+ #
45
+ # order_by_from_params({'sidx' => 'updated_at', 'sord' => 'asc'})
46
+ # => 'updated_at asc'
47
+ #
48
+ def order_by_from_params params
49
+ order_by = params['sidx'] if params['sidx']
50
+ order_by << " #{params['sord']}" if params['sord'] && order_by
51
+ order_by
52
+ end
53
+
54
+ end
55
+ end
56
+ end
57
+
@@ -0,0 +1,5 @@
1
+ String.class_eval do
2
+ def to_json_var
3
+ ActiveSupport::JSON::Variable.new(self)
4
+ end
5
+ end
@@ -0,0 +1,13 @@
1
+ # JqgridForRails
2
+
3
+ require 'jqgrid_for_rails/core_ext'
4
+ require 'jqgrid_for_rails/controllers/helpers'
5
+
6
+ ActionController::Base.send :include, JqgridForRails::Controllers::Helpers
7
+
8
+ %w{ models controllers helpers }.each do |dir|
9
+ path = File.join(File.dirname(__FILE__), 'app', dir)
10
+ $LOAD_PATH << path
11
+ ActiveSupport::Dependencies.autoload_paths << path
12
+ ActiveSupport::Dependencies.autoload_once_paths.delete(path)
13
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :jqgrid_for_rails do
3
+ # # Task goes here
4
+ # end
data/rails/init.rb ADDED
@@ -0,0 +1,2 @@
1
+ # Include hook code here
2
+ require 'jqgrid_for_rails'
@@ -0,0 +1,29 @@
1
+ require 'test/test_helper'
2
+
3
+ class MockController < ApplicationController
4
+ end
5
+
6
+ class ControllerHelpersTest < ActionController::TestCase
7
+
8
+ def setup
9
+ @controller = MockController.new
10
+ end
11
+
12
+ tests MockController
13
+
14
+ test "order_by_from with sidx and sord" do
15
+ params = {'sidx' => 'updated_at', 'sord' => 'desc' }
16
+ assert_equal 'updated_at desc', @controller.order_by_from_params(params)
17
+ end
18
+
19
+ test "order_by_from with sidx" do
20
+ params = {'sidx' => 'updated_at'}
21
+ assert_equal 'updated_at', @controller.order_by_from_params(params)
22
+ end
23
+
24
+ test "order_by_from without sidx" do
25
+ params = {'sord' => 'desc' }
26
+ assert_nil @controller.order_by_from_params(params)
27
+ end
28
+
29
+ end
@@ -0,0 +1,11 @@
1
+ require File.dirname(__FILE__) + '/test_helper.rb'
2
+
3
+ class CoreExtTest < Test::Unit::TestCase
4
+
5
+ def test_string_to_json_var
6
+ js = 'function() { alert("test"); }'
7
+ assert_equal( js.to_json_var, js)
8
+ end
9
+
10
+ end
11
+
data/test/database.yml ADDED
@@ -0,0 +1,22 @@
1
+ sqlite:
2
+ :adapter: sqlite
3
+ :database: vendor/plugins/jqgrid_for_rails/test/jqgrid_for_rails_plugin.sqlite.db
4
+
5
+ sqlite3:
6
+ :adapter: sqlite3
7
+ :database: vendor/plugins/jqgrid_for_rails/test/jqgrid_for_rails_plugin.sqlite3.db
8
+
9
+ postgresql:
10
+ :adapter: postgresql
11
+ :username: postgres
12
+ :password: postgres
13
+ :database: jqgrid_for_rails_plugin_test
14
+ :min_messages: ERROR
15
+
16
+ mysql:
17
+ :adapter: mysql
18
+ :host: localhost
19
+ :username: root
20
+ :password: root
21
+ :database: jqgrid_for_rails_plugin_test
22
+
@@ -0,0 +1,13 @@
1
+ require File.dirname(__FILE__) + '/test_helper.rb'
2
+
3
+ class JqgridForRailsTest < Test::Unit::TestCase
4
+ load_schema
5
+
6
+ class Invoices < ActiveRecord::Base
7
+ end
8
+
9
+ def test_schema_has_loaded_correctly
10
+ assert_equal [], Invoices.all
11
+ end
12
+
13
+ end
@@ -0,0 +1,60 @@
1
+ require File.dirname(__FILE__) + '/test_helper.rb'
2
+
3
+ class MockView < ActionView::Base
4
+ include JqgridsHelper
5
+ end
6
+
7
+ class JqgridsHelperTest < Test::Unit::TestCase
8
+
9
+ def test_jqgrid_small
10
+
11
+ @template = MockView.new
12
+
13
+ grid_id = 'grid_id'
14
+ options = {:html_tags => true}
15
+ grid_options = { :url => "/jqGridModel?model=Wine" }
16
+
17
+ expected = '<table id="'+grid_id+'"></table>' + "\n"
18
+ expected << '<script>' + "\n"
19
+ expected << 'jQuery("#'+grid_id+'").jqGrid({"url":"/jqGridModel?model=Wine"});' + "\n"
20
+ expected << '</script>'
21
+
22
+ assert_equal(expected, @template.jqgrid(grid_id, options , grid_options))
23
+
24
+ end
25
+
26
+ def test_jqgrid_medium
27
+
28
+ @template = MockView.new
29
+
30
+ grid_id = 'grid_id'
31
+ pager_id = 'gridpager'
32
+ grid_options = { :pager => "jQuery('##{pager_id}')".to_json_var }
33
+
34
+ options = {:on_document_ready => true }
35
+ expected = expected_grid(grid_id, pager_id, options)
36
+ assert_equal(expected, @template.jqgrid(grid_id, options, grid_options))
37
+
38
+ options = {:on_document_ready => true, :html_tags => true }
39
+ expected = expected_grid(grid_id, pager_id, options)
40
+ assert_equal(expected, @template.jqgrid(grid_id, options, grid_options))
41
+ end
42
+
43
+ def expected_grid grid_id, pager_id, options
44
+ expected = ''
45
+ expected << '<table id="'+grid_id+'"></table>' + "\n" if options[:html_tags]
46
+ expected << '<div id="'+pager_id+'"></div>' + "\n" if options[:html_tags]
47
+ expected << '<script>' + "\n"
48
+
49
+ js = 'jQuery(document).ready(function() {
50
+ jQuery("#' + grid_id + '").jqGrid({
51
+ "pager":jQuery(\'#' + pager_id + '\')
52
+ });
53
+ jQuery("#grid_id").jqGrid("navGrid", "#gridpager", {});
54
+ });'
55
+ expected << js.gsub(/\n\s+/, '') + "\n"
56
+ expected << '</script>'
57
+
58
+ end
59
+
60
+ end
data/test/schema.rb ADDED
@@ -0,0 +1,12 @@
1
+ ActiveRecord::Schema.define(:version => 0) do
2
+
3
+ create_table :invoices, :force => true do |t|
4
+ t.integer 'invid'
5
+ t.datetime 'invdate'
6
+ t.float 'amount'
7
+ t.float 'tax'
8
+ t.float 'total'
9
+ t.string 'note'
10
+ end
11
+
12
+ end
@@ -0,0 +1,35 @@
1
+ ENV['RAILS_ENV'] = 'test'
2
+ ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
3
+
4
+ require 'test/unit'
5
+ require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
6
+
7
+ def load_schema
8
+ config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
9
+ ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
10
+
11
+ db_adapter = ENV['DB']
12
+
13
+ # no db passed, try one of these fine config-free DBs before bombing.
14
+ db_adapter ||=
15
+ begin
16
+ require 'rubygems'
17
+ require 'sqlite'
18
+ 'sqlite'
19
+ rescue MissingSourceFile
20
+ begin
21
+ require 'sqlite3'
22
+ 'sqlite3'
23
+ rescue MissingSourceFile
24
+ end
25
+ end
26
+
27
+ if db_adapter.nil?
28
+ raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
29
+ end
30
+ ActiveRecord::Base.establish_connection(config[db_adapter])
31
+ load(File.dirname(__FILE__) + "/schema.rb")
32
+ require File.dirname(__FILE__) + '/../rails/init.rb'
33
+
34
+ end
35
+
data/uninstall.rb ADDED
@@ -0,0 +1 @@
1
+ # Uninstall hook code here
metadata ADDED
@@ -0,0 +1,99 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: jqgrid_for_rails
3
+ version: !ruby/object:Gem::Version
4
+ hash: 27
5
+ prerelease: false
6
+ segments:
7
+ - 0
8
+ - 1
9
+ - 0
10
+ version: 0.1.0
11
+ platform: ruby
12
+ authors:
13
+ - Juan Manuel Cuello
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2011-01-06 00:00:00 -03:00
19
+ default_executable:
20
+ dependencies:
21
+ - !ruby/object:Gem::Dependency
22
+ name: will_paginate
23
+ prerelease: false
24
+ requirement: &id001 !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ hash: 3
30
+ segments:
31
+ - 0
32
+ version: "0"
33
+ type: :runtime
34
+ version_requirements: *id001
35
+ description: Simple solution to create jqgrids easily using Rails
36
+ email: juanmacuello@gmail.com
37
+ executables: []
38
+
39
+ extensions: []
40
+
41
+ extra_rdoc_files: []
42
+
43
+ files:
44
+ - .gitignore
45
+ - MIT-LICENSE
46
+ - README.rdoc
47
+ - Rakefile
48
+ - install.rb
49
+ - lib/app/helpers/jqgrids_helper.rb
50
+ - lib/jqgrid_for_rails.rb
51
+ - lib/jqgrid_for_rails/controllers/helpers.rb
52
+ - lib/jqgrid_for_rails/core_ext.rb
53
+ - lib/tasks/jqgrid_for_rails.rake
54
+ - rails/init.rb
55
+ - test/controllers/helpers_test.rb
56
+ - test/core_ext_test.rb
57
+ - test/database.yml
58
+ - test/jqgrid_for_rails_plugin.sqlite3.db
59
+ - test/jqgrid_for_rails_test.rb
60
+ - test/jqgrids_helper_test.rb
61
+ - test/schema.rb
62
+ - test/test_helper.rb
63
+ - uninstall.rb
64
+ has_rdoc: true
65
+ homepage: http://github.com/Juanmcuello/jqgrid_for_rails
66
+ licenses: []
67
+
68
+ post_install_message:
69
+ rdoc_options: []
70
+
71
+ require_paths:
72
+ - lib
73
+ required_ruby_version: !ruby/object:Gem::Requirement
74
+ none: false
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ hash: 3
79
+ segments:
80
+ - 0
81
+ version: "0"
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ none: false
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ hash: 3
88
+ segments:
89
+ - 0
90
+ version: "0"
91
+ requirements: []
92
+
93
+ rubyforge_project:
94
+ rubygems_version: 1.3.7
95
+ signing_key:
96
+ specification_version: 3
97
+ summary: Simple solution to create jqgrids easily using Rails
98
+ test_files: []
99
+