visual_query 0.3.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/MIT-LICENSE +20 -0
- data/README.md +59 -0
- data/Rakefile +23 -0
- data/app/assets/images/visual_query/ajax-loader.gif +0 -0
- data/app/assets/javascripts/visual_query/index.js +288 -0
- data/app/assets/stylesheets/visual_query/visual_query.css +161 -0
- data/app/controllers/queries_controller.rb +157 -0
- data/app/helpers/application_helper.rb +5 -0
- data/app/helpers/queries_helper.rb +43 -0
- data/app/views/queries/_columns.html.erb +5 -0
- data/app/views/queries/_command.html.erb +5 -0
- data/app/views/queries/_command_results_browser.html.erb +1 -0
- data/app/views/queries/_command_save.html.erb +1 -0
- data/app/views/queries/_commands_results.html.erb +2 -0
- data/app/views/queries/_filter.html.erb +6 -0
- data/app/views/queries/_list_all_relations.html.erb +8 -0
- data/app/views/queries/_list_joinable_relations.html.erb +10 -0
- data/app/views/queries/_list_relation.html.erb +8 -0
- data/app/views/queries/_name.html.erb +8 -0
- data/app/views/queries/_results.html.erb +14 -0
- data/app/views/queries/_results_column_filter.html.erb +3 -0
- data/app/views/queries/_results_column_hide.html.erb +3 -0
- data/app/views/queries/_results_column_human_name.html.erb +8 -0
- data/app/views/queries/_results_empty.html.erb +3 -0
- data/app/views/queries/_sort.html.erb +12 -0
- data/app/views/queries/_sort_condition.html.erb +18 -0
- data/app/views/queries/_url_root.html.erb +1 -0
- data/app/views/queries/_warning_large_result_set.html.erb +12 -0
- data/app/views/queries/filters/_boolean.html.erb +6 -0
- data/app/views/queries/filters/_date.html.erb +17 -0
- data/app/views/queries/filters/_datetime.html.erb +1 -0
- data/app/views/queries/filters/_decimal.html.erb +1 -0
- data/app/views/queries/filters/_integer.html.erb +1 -0
- data/app/views/queries/filters/_numeric.html.erb +6 -0
- data/app/views/queries/filters/_string.html.erb +1 -0
- data/app/views/queries/filters/_text.html.erb +6 -0
- data/app/views/queries/index.html.erb +39 -0
- data/app/views/queries/new.html.erb +27 -0
- data/app/views/queries/not_found.html.erb +1 -0
- data/app/views/queries/show.html.erb +40 -0
- data/app/views/queries/sql_form.html.erb +16 -0
- data/config/initializers/visual_query.rb +11 -0
- data/config/routes.rb +26 -0
- data/db/migrate/20130927090319_create_visual_query_schema.rb +9 -0
- data/db/migrate/20130927090400_create_visual_query_metadata_table.rb +16 -0
- data/lib/tasks/visual_query_tasks.rake +12 -0
- data/lib/tutuf/visual_query.rb +6 -0
- data/lib/tutuf/visual_query/base.rb +268 -0
- data/lib/tutuf/visual_query/common.rb +58 -0
- data/lib/tutuf/visual_query/metadata.rb +35 -0
- data/lib/tutuf/visual_query/single.rb +111 -0
- data/lib/tutuf/visual_query/sql.rb +20 -0
- data/lib/visual_query.rb +4 -0
- data/lib/visual_query/engine.rb +4 -0
- data/lib/visual_query/version.rb +3 -0
- data/test/dummy/README.rdoc +261 -0
- data/test/dummy/Rakefile +7 -0
- data/test/dummy/app/assets/javascripts/application.js +15 -0
- data/test/dummy/app/assets/stylesheets/application.css +13 -0
- data/test/dummy/app/controllers/application_controller.rb +3 -0
- data/test/dummy/app/helpers/application_helper.rb +2 -0
- data/test/dummy/app/models/account.rb +3 -0
- data/test/dummy/app/models/address.rb +3 -0
- data/test/dummy/app/models/category.rb +3 -0
- data/test/dummy/app/models/composite_pk.rb +3 -0
- data/test/dummy/app/models/customer.rb +4 -0
- data/test/dummy/app/models/order.rb +4 -0
- data/test/dummy/app/models/person.rb +4 -0
- data/test/dummy/app/models/post.rb +3 -0
- data/test/dummy/app/models/product.rb +4 -0
- data/test/dummy/app/models/product_in.rb +3 -0
- data/test/dummy/app/models/product_out.rb +3 -0
- data/test/dummy/app/views/layouts/application.html.erb +14 -0
- data/test/dummy/config.ru +4 -0
- data/test/dummy/config/application.rb +53 -0
- data/test/dummy/config/boot.rb +10 -0
- data/test/dummy/config/database.yml +12 -0
- data/test/dummy/config/environment.rb +5 -0
- data/test/dummy/config/environments/development.rb +29 -0
- data/test/dummy/config/environments/production.rb +65 -0
- data/test/dummy/config/environments/test.rb +33 -0
- data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
- data/test/dummy/config/initializers/inflections.rb +15 -0
- data/test/dummy/config/initializers/mime_types.rb +5 -0
- data/test/dummy/config/initializers/secret_token.rb +7 -0
- data/test/dummy/config/initializers/session_store.rb +8 -0
- data/test/dummy/config/initializers/visual_query.rb +1 -0
- data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
- data/test/dummy/config/locales/en.yml +5 -0
- data/test/dummy/config/routes.rb +3 -0
- data/test/dummy/db/migrate/20130927112446_create_tables.rb +77 -0
- data/test/dummy/db/structure.sql +651 -0
- data/test/dummy/log/development.log +1548 -0
- data/test/dummy/log/test.log +36575 -0
- data/test/dummy/public/404.html +26 -0
- data/test/dummy/public/422.html +26 -0
- data/test/dummy/public/500.html +25 -0
- data/test/dummy/public/favicon.ico +0 -0
- data/test/dummy/script/rails +6 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/-h/-hj2e_RSTanfbfrP0tso5Q7actRM6_clE5hetFlQ2y8.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/3B/3B_zqoNDfkO8wvAME66zxm9KzQaeDVSjnH0qC08yufM.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/5g/5g7dhxVp4YbZmFw_-T3aU2oYq2Z9Jgtps0CKneXYSS0.cache +2 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/6-/6-CtZO6uG0yfwU8-098Sdy2wnfO0W6DbFu6B6DKYuiw.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/8k/8kFIVN4cTS9KCQt_UIF5s_rcY-bMYlQpM489D98hvP4.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/Au/AukU7t3xLnyCh7qW4u45q9YFmjVcYujmIFbnaOhF4Mo.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/Bm/Bmsq0vYQqlrtfq5s-W8kcfLvwcsPT_6_5XxXt9J_QOw.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/CQ/CQLNg7a2TsUWgc7JXjDkjseMig_dPVm6AvqO2IWk5zg.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/FX/FX9ZXN3HEHR5hPzvxW8rakWEt2ot4IPJyDB67O7KPZk.cache +2 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/Hv/HvOStITEkFHlcJCgaDnND6wzPw4dMmdAdZB1Xm6JfSA.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/NW/NWCtuFzfIgixavqY71NIAa4ajbsXxRuiLNjceHgQ24M.cache +2 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/Ta/TaG641Ow168nkagg10mh6zuWS8RwWuawpHuMGakCVjU.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/VN/VNCapNKJLeponthNeFJhaBYs92UBT3P8PugENHP0474.cache +2 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/VR/VRi0Hz7tc62H5Of9XVjyAk7vSNmMr8xeYowo6lSBnZg.cache +2 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/Vg/Vgl_u6t3BvczgGi_ZJlyyo7xYSe-GgEshLofx-3QorI.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/Vq/VqGJMF3Cpvp3fw2IEIkE2tzdFo_OdcEmxN58BQwbVDY.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/W6/W6DnXCIMHJ2i5hUkEiNeDLroWxW3VU18nq292n5jlts.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/Z7/Z7fH8ST-O3GMnDUKvtKHHTSObfH2Nbs0J1QS79i80yE.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/Zh/ZhrmuPgfbHthzikN8QSHR0Q0bLtSYS1Bzl9HauWeDfU.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/bY/bYzYCY_bAGQGVGMbcxtKIhUYrgDQhmQVTmK50JrMNb8.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/eT/eTmCDSnc2m9ER5Cn85g84xyTkVLWKLbbwPFQo8eUAIg.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/h-/h-taE7cHlbq76GUb5kHenjih_y66mO0w0lIZs7vY-0s.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/ji/jikmiWyu-cXN_ZJ4hgLc3kuCAY-QJY2jmPeXS4_9vZY.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/kC/kCijps52gsNlkYgT2Qzdz9UcSaxhcMGNfNL7MIiWk54.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/kQ/kQt-OsUDJg_sl1be-FqJ6Vhw4XVguw9_msZEwXP0Nh0.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/nd/ndbe-ZZWBqU5gLx5nxauCFvv963Zm3xqVEwVYQ7X_X8.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/q6/q6BYa32YJF11eGVapO4ouNl6gayPIsARgMavlzZmoi0.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/sm/sm7AdmddDYbFx4-eo_y_kaZspanmc-jiJeM8j2DXX5k.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/ux/uxPH9lLOW42lEQxJXnBizEObZReD8qkz6Eb6fdS6Ur4.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/wn/wn0ayyM-chRdwEPI11SLkFT-7G2-GcOX8UIIC2kOWLY.cache +1 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/x7/x7KkTV3ibfIEysLB_ug5bfmnn2VLV_BldukPR3EoPBk.cache +0 -0
- data/test/dummy/tmp/cache/assets/test/sprockets/v3.0/xK/xKo0PfDcZuMh8oO-6Gr4j4S8eR2qUNY9Gau4kAxKIH0.cache +1 -0
- data/test/fixtures/accounts.yml +4 -0
- data/test/fixtures/categories.yml +3 -0
- data/test/fixtures/categories_posts.yml +3 -0
- data/test/fixtures/people.yml +8 -0
- data/test/fixtures/posts.yml +8 -0
- data/test/fixtures/product_ins.yml +15 -0
- data/test/fixtures/product_outs.yml +5 -0
- data/test/fixtures/products.yml +6 -0
- data/test/fixtures/saved_queries.rb +7 -0
- data/test/functional/queries_controller_test.rb +267 -0
- data/test/functional/routes_test.rb +111 -0
- data/test/integration/navigation_test.rb +10 -0
- data/test/test_helper.rb +15 -0
- data/test/unit/metadata_test.rb +10 -0
- data/test/unit/sql_test.rb +37 -0
- data/test/unit/visual_query_test.rb +648 -0
- metadata +381 -0
@@ -0,0 +1,58 @@
|
|
1
|
+
# -*- encoding : utf-8 -*-
|
2
|
+
module Tutuf
|
3
|
+
module VisualQuery
|
4
|
+
class Common
|
5
|
+
class << self
|
6
|
+
def connection
|
7
|
+
ActiveRecord::Base.connection
|
8
|
+
end
|
9
|
+
|
10
|
+
#delegates to PostgreSQL raw connection
|
11
|
+
def quote_ident(str)
|
12
|
+
connection.raw_connection.quote_ident(str)
|
13
|
+
end
|
14
|
+
|
15
|
+
def quote_relation_name(name)
|
16
|
+
if String === name # in default schema
|
17
|
+
quote_ident(name)
|
18
|
+
elsif Hash === name
|
19
|
+
"#{!name['schema'].blank? ? quote_ident(name['schema']) + '.' : ''}#{quote_ident(name['rel_name'])}"
|
20
|
+
end
|
21
|
+
end
|
22
|
+
end
|
23
|
+
|
24
|
+
# Parameters of the block: +schema+, +relation_name+, +column_name+, +operator+, +value+
|
25
|
+
def filters_to_a(&block)
|
26
|
+
parse_filters(filters, &block)
|
27
|
+
end
|
28
|
+
|
29
|
+
protected
|
30
|
+
def connection
|
31
|
+
self.class.connection
|
32
|
+
end
|
33
|
+
|
34
|
+
def quote_ident(str)
|
35
|
+
self.class.quote_ident(str)
|
36
|
+
end
|
37
|
+
|
38
|
+
def quote_relation_name(name)
|
39
|
+
self.class.quote_relation_name(name)
|
40
|
+
end
|
41
|
+
|
42
|
+
def parse_filters(filters)
|
43
|
+
return [] if filters.blank? || (Hash === filters) # old version
|
44
|
+
res = []
|
45
|
+
filters.each do |filter|
|
46
|
+
schema, rel_name, col_name, op, val = [filter['schema'], filter['rel_name'], filter['col_name'], filter['op'], filter['val']]
|
47
|
+
if (!val.blank? || ( val.blank? && op == '=' ))
|
48
|
+
val = "%#{val}%" if (op == 'LIKE' || op == 'ILIKE')
|
49
|
+
res << yield(schema,rel_name,col_name,op,val)
|
50
|
+
elsif op == 'IS NULL'
|
51
|
+
res << yield(schema,rel_name,col_name,"IS","NULL")
|
52
|
+
end
|
53
|
+
end
|
54
|
+
res
|
55
|
+
end
|
56
|
+
end
|
57
|
+
end
|
58
|
+
end
|
@@ -0,0 +1,35 @@
|
|
1
|
+
# -*- encoding : utf-8 -*-
|
2
|
+
module Tutuf
|
3
|
+
module VisualQuery
|
4
|
+
class Metadata < ActiveRecord::Base
|
5
|
+
self.table_name = 'tutuf_visual_query_metadata'
|
6
|
+
|
7
|
+
class JSON
|
8
|
+
def load(text)
|
9
|
+
::JSON.parse(text)
|
10
|
+
end
|
11
|
+
|
12
|
+
def dump(text)
|
13
|
+
::JSON.dump(text)
|
14
|
+
end
|
15
|
+
end
|
16
|
+
|
17
|
+
serialize :params, JSON.new
|
18
|
+
|
19
|
+
validates :name, :presence => true,
|
20
|
+
:uniqueness => true,
|
21
|
+
:length => { :maximum => 63, :too_long => "не може да е по-дълго от 63 байта" }
|
22
|
+
|
23
|
+
default_scope -> { order(:name) }
|
24
|
+
|
25
|
+
before_save do
|
26
|
+
%w(controller action authenticity_token sort_conditions utf8).each{ |p| params.delete(p) }
|
27
|
+
return true
|
28
|
+
end
|
29
|
+
|
30
|
+
def locked?
|
31
|
+
params['readonly']
|
32
|
+
end
|
33
|
+
end
|
34
|
+
end
|
35
|
+
end
|
@@ -0,0 +1,111 @@
|
|
1
|
+
# -*- encoding : utf-8 -*-
|
2
|
+
module Tutuf
|
3
|
+
module VisualQuery
|
4
|
+
class Single < Common
|
5
|
+
def initialize(params)
|
6
|
+
@relations = parse_relations(params['relations'])
|
7
|
+
@filters = params['filters']
|
8
|
+
@parsed_filters = filters_to_a do |schema, rel_name, col_name, op, val|
|
9
|
+
"#{quote_column_name('schema' => schema, 'rel_name'=>rel_name,'col_name' => col_name)} #{sanitize_operator(op)} #{ val == 'NULL' ? val : quote(val) }"
|
10
|
+
end.join(" AND ")
|
11
|
+
@join_conditions = params['join_conditions']
|
12
|
+
if params['action'] == "create"
|
13
|
+
@parsed_columns = columns_to_sql_for_saving(params['columns'],params['all_columns'],params['all_selected_columns'],params['balanced'])
|
14
|
+
else
|
15
|
+
@parsed_columns = columns_to_sql(params['columns'],params['all_columns'])
|
16
|
+
end
|
17
|
+
|
18
|
+
@sort_conditions = []
|
19
|
+
unless params['sort_conditions'].blank?
|
20
|
+
params['sort_conditions'].map do |key, val|
|
21
|
+
if params['all_columns'].detect{ |all| val['rel_name'] == all['rel_name'] && val['col_name'] == all['col_name'] } &&
|
22
|
+
( val['direction'].blank? || val['direction'] == 'ASC' || val['direction'] == 'DESC' )
|
23
|
+
@sort_conditions[key.to_i] = val
|
24
|
+
end
|
25
|
+
end
|
26
|
+
@sort_conditions.compact!
|
27
|
+
end
|
28
|
+
end
|
29
|
+
|
30
|
+
attr_reader :parsed_columns, :relations, :parsed_filters, :filters, :join_conditions
|
31
|
+
|
32
|
+
def query
|
33
|
+
return nil if relations.nil? || relations.empty?
|
34
|
+
# debugger
|
35
|
+
query_string = "SELECT #{parsed_columns} FROM #{join_relations}"
|
36
|
+
query_string += " WHERE #{parsed_filters}" unless parsed_filters.blank?
|
37
|
+
query_string += " ORDER BY #{@sort_conditions.map{ |sc| "#{quote_ident(sc['rel_name'])}.#{quote_ident(sc['col_name'])} #{sc['direction']}" }.join(',')}" unless @sort_conditions.blank?
|
38
|
+
query_string.force_encoding('UTF-8')
|
39
|
+
end
|
40
|
+
|
41
|
+
protected
|
42
|
+
|
43
|
+
def quote(str)
|
44
|
+
ActiveRecord::Base.sanitize(str)
|
45
|
+
end
|
46
|
+
|
47
|
+
def quote_column_name(qn)
|
48
|
+
"#{qn['schema'] ? quote_ident(qn['schema']) + '.' : ''}#{quote_ident(qn['rel_name'])}.#{quote_ident(qn['col_name'])}"
|
49
|
+
end
|
50
|
+
|
51
|
+
private
|
52
|
+
def sanitize_operator(str)
|
53
|
+
if %w(AND OR LIKE ILIKE IS >= > = < <= != <>).member?(str)
|
54
|
+
return str
|
55
|
+
else
|
56
|
+
raise %(Unrecognized operator "#{str}" in SQL query. Possible injection attack!)
|
57
|
+
end
|
58
|
+
end
|
59
|
+
|
60
|
+
def sanitize_join_type(str)
|
61
|
+
if %w(INNER LEFT RIGHT FULL).member?(str)
|
62
|
+
return str
|
63
|
+
else
|
64
|
+
return "INNER"
|
65
|
+
end
|
66
|
+
end
|
67
|
+
|
68
|
+
def columns_to_sql(selected,all)
|
69
|
+
return if selected.blank? || all.blank?
|
70
|
+
all.map{|c| selected.member?(c) ? quote_column_name(c) : "NULL"}.join(",")
|
71
|
+
end
|
72
|
+
|
73
|
+
# TODO: select proper cols in columns_to_sql_for_saving for balanced queries
|
74
|
+
def columns_to_sql_for_saving(selected,all_selected,all,balanced = false)
|
75
|
+
return if selected.blank?
|
76
|
+
if balanced
|
77
|
+
all.map do |c|
|
78
|
+
if selected.member?(c)
|
79
|
+
"#{quote_column_name(c)} AS #{quote_ident(c['save_name'])}"
|
80
|
+
elsif !all_selected.member?(c) && relations.map{|r| r['rel_name']}.member?(c['rel_name']) # c is hidden column
|
81
|
+
nil
|
82
|
+
else # c is not in a relation in this query
|
83
|
+
"NULL AS #{quote_ident(c['save_name'])}"
|
84
|
+
end
|
85
|
+
end.compact.join(",")
|
86
|
+
else
|
87
|
+
selected.map { |c| "#{quote_column_name(c)} AS #{quote_ident(c['save_name'])}"}.join(",")
|
88
|
+
end
|
89
|
+
end
|
90
|
+
|
91
|
+
def parse_relations(relations)
|
92
|
+
relations.map{|r| quote_relation_name(r)} unless relations.blank?
|
93
|
+
end
|
94
|
+
|
95
|
+
# [{'left_rel_name'=>"incoming_invoices",
|
96
|
+
# 'left_col_name'=>"payment_method_id",
|
97
|
+
# 'right_rel_name'=>"payment_methods",
|
98
|
+
# 'right_col_name'=>"id",
|
99
|
+
# 'type' => "FULL"}, ...]
|
100
|
+
def join_relations
|
101
|
+
return relations.first if join_conditions.blank?
|
102
|
+
join_conditions.inject("") do |res, jc|
|
103
|
+
res << quote_relation_name(jc['left_rel_name']) if res.blank?
|
104
|
+
res << " #{sanitize_join_type(jc['type'])} JOIN #{quote_relation_name(jc['right_rel_name'])}"
|
105
|
+
res << " ON " << %w(left right).map{|t| quote_column_name('rel_name' => jc["#{t}_rel_name"], 'col_name' => jc["#{t}_col_name"])}.join(" = ")
|
106
|
+
res
|
107
|
+
end
|
108
|
+
end
|
109
|
+
end
|
110
|
+
end
|
111
|
+
end
|
@@ -0,0 +1,20 @@
|
|
1
|
+
# -*- encoding : utf-8 -*-
|
2
|
+
module Tutuf
|
3
|
+
module VisualQuery
|
4
|
+
class Sql < Common
|
5
|
+
def initialize(params)
|
6
|
+
@sql = params['sql']
|
7
|
+
end
|
8
|
+
|
9
|
+
attr_writer :sql
|
10
|
+
|
11
|
+
def filters
|
12
|
+
[]
|
13
|
+
end
|
14
|
+
|
15
|
+
def query
|
16
|
+
@sql
|
17
|
+
end
|
18
|
+
end
|
19
|
+
end
|
20
|
+
end
|
data/lib/visual_query.rb
ADDED
@@ -0,0 +1,261 @@
|
|
1
|
+
== Welcome to Rails
|
2
|
+
|
3
|
+
Rails is a web-application framework that includes everything needed to create
|
4
|
+
database-backed web applications according to the Model-View-Control pattern.
|
5
|
+
|
6
|
+
This pattern splits the view (also called the presentation) into "dumb"
|
7
|
+
templates that are primarily responsible for inserting pre-built data in between
|
8
|
+
HTML tags. The model contains the "smart" domain objects (such as Account,
|
9
|
+
Product, Person, Post) that holds all the business logic and knows how to
|
10
|
+
persist themselves to a database. The controller handles the incoming requests
|
11
|
+
(such as Save New Account, Update Product, Show Post) by manipulating the model
|
12
|
+
and directing data to the view.
|
13
|
+
|
14
|
+
In Rails, the model is handled by what's called an object-relational mapping
|
15
|
+
layer entitled Active Record. This layer allows you to present the data from
|
16
|
+
database rows as objects and embellish these data objects with business logic
|
17
|
+
methods. You can read more about Active Record in
|
18
|
+
link:files/vendor/rails/activerecord/README.html.
|
19
|
+
|
20
|
+
The controller and view are handled by the Action Pack, which handles both
|
21
|
+
layers by its two parts: Action View and Action Controller. These two layers
|
22
|
+
are bundled in a single package due to their heavy interdependence. This is
|
23
|
+
unlike the relationship between the Active Record and Action Pack that is much
|
24
|
+
more separate. Each of these packages can be used independently outside of
|
25
|
+
Rails. You can read more about Action Pack in
|
26
|
+
link:files/vendor/rails/actionpack/README.html.
|
27
|
+
|
28
|
+
|
29
|
+
== Getting Started
|
30
|
+
|
31
|
+
1. At the command prompt, create a new Rails application:
|
32
|
+
<tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
|
33
|
+
|
34
|
+
2. Change directory to <tt>myapp</tt> and start the web server:
|
35
|
+
<tt>cd myapp; rails server</tt> (run with --help for options)
|
36
|
+
|
37
|
+
3. Go to http://localhost:3000/ and you'll see:
|
38
|
+
"Welcome aboard: You're riding Ruby on Rails!"
|
39
|
+
|
40
|
+
4. Follow the guidelines to start developing your application. You can find
|
41
|
+
the following resources handy:
|
42
|
+
|
43
|
+
* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
|
44
|
+
* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
|
45
|
+
|
46
|
+
|
47
|
+
== Debugging Rails
|
48
|
+
|
49
|
+
Sometimes your application goes wrong. Fortunately there are a lot of tools that
|
50
|
+
will help you debug it and get it back on the rails.
|
51
|
+
|
52
|
+
First area to check is the application log files. Have "tail -f" commands
|
53
|
+
running on the server.log and development.log. Rails will automatically display
|
54
|
+
debugging and runtime information to these files. Debugging info will also be
|
55
|
+
shown in the browser on requests from 127.0.0.1.
|
56
|
+
|
57
|
+
You can also log your own messages directly into the log file from your code
|
58
|
+
using the Ruby logger class from inside your controllers. Example:
|
59
|
+
|
60
|
+
class WeblogController < ActionController::Base
|
61
|
+
def destroy
|
62
|
+
@weblog = Weblog.find(params[:id])
|
63
|
+
@weblog.destroy
|
64
|
+
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
|
65
|
+
end
|
66
|
+
end
|
67
|
+
|
68
|
+
The result will be a message in your log file along the lines of:
|
69
|
+
|
70
|
+
Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
|
71
|
+
|
72
|
+
More information on how to use the logger is at http://www.ruby-doc.org/core/
|
73
|
+
|
74
|
+
Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
|
75
|
+
several books available online as well:
|
76
|
+
|
77
|
+
* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
|
78
|
+
* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
|
79
|
+
|
80
|
+
These two books will bring you up to speed on the Ruby language and also on
|
81
|
+
programming in general.
|
82
|
+
|
83
|
+
|
84
|
+
== Debugger
|
85
|
+
|
86
|
+
Debugger support is available through the debugger command when you start your
|
87
|
+
Mongrel or WEBrick server with --debugger. This means that you can break out of
|
88
|
+
execution at any point in the code, investigate and change the model, and then,
|
89
|
+
resume execution! You need to install ruby-debug to run the server in debugging
|
90
|
+
mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
|
91
|
+
|
92
|
+
class WeblogController < ActionController::Base
|
93
|
+
def index
|
94
|
+
@posts = Post.all
|
95
|
+
debugger
|
96
|
+
end
|
97
|
+
end
|
98
|
+
|
99
|
+
So the controller will accept the action, run the first line, then present you
|
100
|
+
with a IRB prompt in the server window. Here you can do things like:
|
101
|
+
|
102
|
+
>> @posts.inspect
|
103
|
+
=> "[#<Post:0x14a6be8
|
104
|
+
@attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
|
105
|
+
#<Post:0x14a6620
|
106
|
+
@attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
|
107
|
+
>> @posts.first.title = "hello from a debugger"
|
108
|
+
=> "hello from a debugger"
|
109
|
+
|
110
|
+
...and even better, you can examine how your runtime objects actually work:
|
111
|
+
|
112
|
+
>> f = @posts.first
|
113
|
+
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
|
114
|
+
>> f.
|
115
|
+
Display all 152 possibilities? (y or n)
|
116
|
+
|
117
|
+
Finally, when you're ready to resume execution, you can enter "cont".
|
118
|
+
|
119
|
+
|
120
|
+
== Console
|
121
|
+
|
122
|
+
The console is a Ruby shell, which allows you to interact with your
|
123
|
+
application's domain model. Here you'll have all parts of the application
|
124
|
+
configured, just like it is when the application is running. You can inspect
|
125
|
+
domain models, change values, and save to the database. Starting the script
|
126
|
+
without arguments will launch it in the development environment.
|
127
|
+
|
128
|
+
To start the console, run <tt>rails console</tt> from the application
|
129
|
+
directory.
|
130
|
+
|
131
|
+
Options:
|
132
|
+
|
133
|
+
* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
|
134
|
+
made to the database.
|
135
|
+
* Passing an environment name as an argument will load the corresponding
|
136
|
+
environment. Example: <tt>rails console production</tt>.
|
137
|
+
|
138
|
+
To reload your controllers and models after launching the console run
|
139
|
+
<tt>reload!</tt>
|
140
|
+
|
141
|
+
More information about irb can be found at:
|
142
|
+
link:http://www.rubycentral.org/pickaxe/irb.html
|
143
|
+
|
144
|
+
|
145
|
+
== dbconsole
|
146
|
+
|
147
|
+
You can go to the command line of your database directly through <tt>rails
|
148
|
+
dbconsole</tt>. You would be connected to the database with the credentials
|
149
|
+
defined in database.yml. Starting the script without arguments will connect you
|
150
|
+
to the development database. Passing an argument will connect you to a different
|
151
|
+
database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
|
152
|
+
PostgreSQL and SQLite 3.
|
153
|
+
|
154
|
+
== Description of Contents
|
155
|
+
|
156
|
+
The default directory structure of a generated Ruby on Rails application:
|
157
|
+
|
158
|
+
|-- app
|
159
|
+
| |-- assets
|
160
|
+
| |-- images
|
161
|
+
| |-- javascripts
|
162
|
+
| `-- stylesheets
|
163
|
+
| |-- controllers
|
164
|
+
| |-- helpers
|
165
|
+
| |-- mailers
|
166
|
+
| |-- models
|
167
|
+
| `-- views
|
168
|
+
| `-- layouts
|
169
|
+
|-- config
|
170
|
+
| |-- environments
|
171
|
+
| |-- initializers
|
172
|
+
| `-- locales
|
173
|
+
|-- db
|
174
|
+
|-- doc
|
175
|
+
|-- lib
|
176
|
+
| `-- tasks
|
177
|
+
|-- log
|
178
|
+
|-- public
|
179
|
+
|-- script
|
180
|
+
|-- test
|
181
|
+
| |-- fixtures
|
182
|
+
| |-- functional
|
183
|
+
| |-- integration
|
184
|
+
| |-- performance
|
185
|
+
| `-- unit
|
186
|
+
|-- tmp
|
187
|
+
| |-- cache
|
188
|
+
| |-- pids
|
189
|
+
| |-- sessions
|
190
|
+
| `-- sockets
|
191
|
+
`-- vendor
|
192
|
+
|-- assets
|
193
|
+
`-- stylesheets
|
194
|
+
`-- plugins
|
195
|
+
|
196
|
+
app
|
197
|
+
Holds all the code that's specific to this particular application.
|
198
|
+
|
199
|
+
app/assets
|
200
|
+
Contains subdirectories for images, stylesheets, and JavaScript files.
|
201
|
+
|
202
|
+
app/controllers
|
203
|
+
Holds controllers that should be named like weblogs_controller.rb for
|
204
|
+
automated URL mapping. All controllers should descend from
|
205
|
+
ApplicationController which itself descends from ActionController::Base.
|
206
|
+
|
207
|
+
app/models
|
208
|
+
Holds models that should be named like post.rb. Models descend from
|
209
|
+
ActiveRecord::Base by default.
|
210
|
+
|
211
|
+
app/views
|
212
|
+
Holds the template files for the view that should be named like
|
213
|
+
weblogs/index.html.erb for the WeblogsController#index action. All views use
|
214
|
+
eRuby syntax by default.
|
215
|
+
|
216
|
+
app/views/layouts
|
217
|
+
Holds the template files for layouts to be used with views. This models the
|
218
|
+
common header/footer method of wrapping views. In your views, define a layout
|
219
|
+
using the <tt>layout :default</tt> and create a file named default.html.erb.
|
220
|
+
Inside default.html.erb, call <% yield %> to render the view using this
|
221
|
+
layout.
|
222
|
+
|
223
|
+
app/helpers
|
224
|
+
Holds view helpers that should be named like weblogs_helper.rb. These are
|
225
|
+
generated for you automatically when using generators for controllers.
|
226
|
+
Helpers can be used to wrap functionality for your views into methods.
|
227
|
+
|
228
|
+
config
|
229
|
+
Configuration files for the Rails environment, the routing map, the database,
|
230
|
+
and other dependencies.
|
231
|
+
|
232
|
+
db
|
233
|
+
Contains the database schema in schema.rb. db/migrate contains all the
|
234
|
+
sequence of Migrations for your schema.
|
235
|
+
|
236
|
+
doc
|
237
|
+
This directory is where your application documentation will be stored when
|
238
|
+
generated using <tt>rake doc:app</tt>
|
239
|
+
|
240
|
+
lib
|
241
|
+
Application specific libraries. Basically, any kind of custom code that
|
242
|
+
doesn't belong under controllers, models, or helpers. This directory is in
|
243
|
+
the load path.
|
244
|
+
|
245
|
+
public
|
246
|
+
The directory available for the web server. Also contains the dispatchers and the
|
247
|
+
default HTML files. This should be set as the DOCUMENT_ROOT of your web
|
248
|
+
server.
|
249
|
+
|
250
|
+
script
|
251
|
+
Helper scripts for automation and generation.
|
252
|
+
|
253
|
+
test
|
254
|
+
Unit and functional tests along with fixtures. When using the rails generate
|
255
|
+
command, template test files will be generated for you and placed in this
|
256
|
+
directory.
|
257
|
+
|
258
|
+
vendor
|
259
|
+
External libraries that the application depends on. Also includes the plugins
|
260
|
+
subdirectory. If the app has frozen rails, those gems also go here, under
|
261
|
+
vendor/rails/. This directory is in the load path.
|