activerecord-turntable 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (130) hide show
  1. data/.document +5 -0
  2. data/.gitignore +25 -0
  3. data/.rspec +3 -0
  4. data/Gemfile +25 -0
  5. data/Guardfile +9 -0
  6. data/LICENSE.txt +20 -0
  7. data/README.rdoc +290 -0
  8. data/Rakefile +101 -0
  9. data/activerecord-turntable.gemspec +47 -0
  10. data/lib/active_record/turntable.rb +58 -0
  11. data/lib/active_record/turntable/active_record_ext.rb +26 -0
  12. data/lib/active_record/turntable/active_record_ext/.gitkeep +0 -0
  13. data/lib/active_record/turntable/active_record_ext/abstract_adapter.rb +50 -0
  14. data/lib/active_record/turntable/active_record_ext/clever_load.rb +90 -0
  15. data/lib/active_record/turntable/active_record_ext/fixtures.rb +131 -0
  16. data/lib/active_record/turntable/active_record_ext/log_subscriber.rb +64 -0
  17. data/lib/active_record/turntable/active_record_ext/persistence.rb +95 -0
  18. data/lib/active_record/turntable/active_record_ext/schema_dumper.rb +107 -0
  19. data/lib/active_record/turntable/active_record_ext/sequencer.rb +28 -0
  20. data/lib/active_record/turntable/active_record_ext/transactions.rb +33 -0
  21. data/lib/active_record/turntable/algorithm.rb +7 -0
  22. data/lib/active_record/turntable/algorithm/.gitkeep +0 -0
  23. data/lib/active_record/turntable/algorithm/base.rb +11 -0
  24. data/lib/active_record/turntable/algorithm/range_algorithm.rb +37 -0
  25. data/lib/active_record/turntable/algorithm/range_bsearch_algorithm.rb +41 -0
  26. data/lib/active_record/turntable/base.rb +130 -0
  27. data/lib/active_record/turntable/cluster.rb +70 -0
  28. data/lib/active_record/turntable/compatible.rb +19 -0
  29. data/lib/active_record/turntable/config.rb +24 -0
  30. data/lib/active_record/turntable/connection_proxy.rb +218 -0
  31. data/lib/active_record/turntable/connection_proxy/mixable.rb +39 -0
  32. data/lib/active_record/turntable/error.rb +8 -0
  33. data/lib/active_record/turntable/helpers.rb +5 -0
  34. data/lib/active_record/turntable/helpers/test_helper.rb +25 -0
  35. data/lib/active_record/turntable/master_shard.rb +28 -0
  36. data/lib/active_record/turntable/migration.rb +132 -0
  37. data/lib/active_record/turntable/mixer.rb +203 -0
  38. data/lib/active_record/turntable/mixer/fader.rb +34 -0
  39. data/lib/active_record/turntable/mixer/fader/calculate_shards_sum_result.rb +15 -0
  40. data/lib/active_record/turntable/mixer/fader/insert_shards_merge_result.rb +24 -0
  41. data/lib/active_record/turntable/mixer/fader/select_shards_merge_result.rb +22 -0
  42. data/lib/active_record/turntable/mixer/fader/specified_shard.rb +12 -0
  43. data/lib/active_record/turntable/mixer/fader/update_shards_merge_result.rb +17 -0
  44. data/lib/active_record/turntable/pool_proxy.rb +56 -0
  45. data/lib/active_record/turntable/rack.rb +5 -0
  46. data/lib/active_record/turntable/rack/connection_management.rb +18 -0
  47. data/lib/active_record/turntable/railtie.rb +14 -0
  48. data/lib/active_record/turntable/railties/databases.rake +205 -0
  49. data/lib/active_record/turntable/seq_shard.rb +14 -0
  50. data/lib/active_record/turntable/sequencer.rb +46 -0
  51. data/lib/active_record/turntable/sequencer/api.rb +36 -0
  52. data/lib/active_record/turntable/sequencer/mysql.rb +32 -0
  53. data/lib/active_record/turntable/shard.rb +48 -0
  54. data/lib/active_record/turntable/sql_tree_patch.rb +199 -0
  55. data/lib/active_record/turntable/version.rb +5 -0
  56. data/lib/activerecord-turntable.rb +2 -0
  57. data/lib/generators/active_record/turntable/install_generator.rb +14 -0
  58. data/lib/generators/templates/turntable.yml +40 -0
  59. data/sample_app/.gitignore +16 -0
  60. data/sample_app/Gemfile +41 -0
  61. data/sample_app/README.rdoc +261 -0
  62. data/sample_app/Rakefile +7 -0
  63. data/sample_app/app/assets/images/rails.png +0 -0
  64. data/sample_app/app/assets/javascripts/application.js +15 -0
  65. data/sample_app/app/assets/stylesheets/application.css +13 -0
  66. data/sample_app/app/controllers/application_controller.rb +3 -0
  67. data/sample_app/app/helpers/application_helper.rb +2 -0
  68. data/sample_app/app/mailers/.gitkeep +0 -0
  69. data/sample_app/app/models/.gitkeep +0 -0
  70. data/sample_app/app/models/user.rb +4 -0
  71. data/sample_app/app/views/layouts/application.html.erb +14 -0
  72. data/sample_app/config.ru +4 -0
  73. data/sample_app/config/application.rb +65 -0
  74. data/sample_app/config/boot.rb +6 -0
  75. data/sample_app/config/database.yml +70 -0
  76. data/sample_app/config/environment.rb +5 -0
  77. data/sample_app/config/environments/development.rb +37 -0
  78. data/sample_app/config/environments/production.rb +67 -0
  79. data/sample_app/config/environments/test.rb +37 -0
  80. data/sample_app/config/initializers/backtrace_silencers.rb +7 -0
  81. data/sample_app/config/initializers/inflections.rb +15 -0
  82. data/sample_app/config/initializers/mime_types.rb +5 -0
  83. data/sample_app/config/initializers/secret_token.rb +7 -0
  84. data/sample_app/config/initializers/session_store.rb +8 -0
  85. data/sample_app/config/initializers/wrap_parameters.rb +14 -0
  86. data/sample_app/config/locales/en.yml +5 -0
  87. data/sample_app/config/routes.rb +58 -0
  88. data/sample_app/config/turntable.yml +64 -0
  89. data/sample_app/db/migrate/20120316073058_create_users.rb +11 -0
  90. data/sample_app/db/seeds.rb +7 -0
  91. data/sample_app/lib/assets/.gitkeep +0 -0
  92. data/sample_app/lib/tasks/.gitkeep +0 -0
  93. data/sample_app/log/.gitkeep +0 -0
  94. data/sample_app/public/404.html +26 -0
  95. data/sample_app/public/422.html +26 -0
  96. data/sample_app/public/500.html +25 -0
  97. data/sample_app/public/favicon.ico +0 -0
  98. data/sample_app/public/index.html +241 -0
  99. data/sample_app/public/robots.txt +5 -0
  100. data/sample_app/script/rails +6 -0
  101. data/sample_app/vendor/assets/javascripts/.gitkeep +0 -0
  102. data/sample_app/vendor/assets/stylesheets/.gitkeep +0 -0
  103. data/sample_app/vendor/plugins/.gitkeep +0 -0
  104. data/script/performance/algorithm +32 -0
  105. data/spec/active_record/turntable/active_record_ext/clever_load_spec.rb +81 -0
  106. data/spec/active_record/turntable/active_record_ext/persistence_spec.rb +151 -0
  107. data/spec/active_record/turntable/algorithm/range_algorithm_spec.rb +35 -0
  108. data/spec/active_record/turntable/algorithm_spec.rb +69 -0
  109. data/spec/active_record/turntable/base_spec.rb +13 -0
  110. data/spec/active_record/turntable/cluster_spec.rb +18 -0
  111. data/spec/active_record/turntable/config_spec.rb +17 -0
  112. data/spec/active_record/turntable/connection_proxy_spec.rb +186 -0
  113. data/spec/active_record/turntable/finder_spec.rb +27 -0
  114. data/spec/active_record/turntable/mixer/fader_spec.rb +4 -0
  115. data/spec/active_record/turntable/mixer_spec.rb +114 -0
  116. data/spec/active_record/turntable/shard_spec.rb +21 -0
  117. data/spec/active_record/turntable_spec.rb +30 -0
  118. data/spec/config/database.yml +45 -0
  119. data/spec/config/turntable.yml +17 -0
  120. data/spec/fabricators/.gitkeep +0 -0
  121. data/spec/fabricators/turntable_fabricator.rb +14 -0
  122. data/spec/migrations/.gitkeep +0 -0
  123. data/spec/migrations/001_create_users.rb +16 -0
  124. data/spec/migrations/002_create_user_statuses.rb +16 -0
  125. data/spec/migrations/003_create_cards.rb +14 -0
  126. data/spec/migrations/004_create_cards_users.rb +15 -0
  127. data/spec/spec_helper.rb +23 -0
  128. data/spec/test_models.rb +27 -0
  129. data/spec/turntable_helper.rb +29 -0
  130. metadata +367 -0
@@ -0,0 +1,48 @@
1
+ module ActiveRecord::Turntable
2
+ class Shard
3
+ DEFAULT_CONFIG = {
4
+ "connection" => (defined?(Rails) ? Rails.env : "development")
5
+ }.with_indifferent_access
6
+
7
+ def initialize(shard_spec)
8
+ @config = DEFAULT_CONFIG.merge(shard_spec)
9
+ @name = @config["connection"]
10
+ end
11
+
12
+ def connection_pool
13
+ @connection_pool ||= retrieve_connection_pool
14
+ end
15
+
16
+ def connection
17
+ connection = connection_pool.connection
18
+ connection.turntable_shard_name = name
19
+ connection
20
+ end
21
+
22
+ def name
23
+ @name
24
+ end
25
+
26
+ private
27
+
28
+ def retrieve_connection_pool
29
+ ActiveRecord::Base.turntable_connections[name] ||=
30
+ begin
31
+ config = ActiveRecord::Base.configurations[Rails.env]["shards"][name]
32
+ raise ArgumentError, "Unknown database config: #{name}, have #{ActiveRecord::Base.configurations.inspect}" unless config
33
+ ActiveRecord::ConnectionAdapters::ConnectionPool.new(spec_for(config))
34
+ end
35
+ end
36
+
37
+ def spec_for(config)
38
+ begin
39
+ require "active_record/connection_adapters/#{config['adapter']}_adapter"
40
+ rescue LoadError => e
41
+ raise "Please install the #{config['adapter']} adapter: `gem install activerecord-#{config['adapter']}-adapter` (#{e})"
42
+ end
43
+ adapter_method = "#{config['adapter']}_connection"
44
+ ActiveRecord::Base::ConnectionSpecification.new(config, adapter_method)
45
+ end
46
+ end
47
+ end
48
+
@@ -0,0 +1,199 @@
1
+ require 'sql_tree'
2
+ require 'active_support/core_ext/kernel/reporting'
3
+
4
+ module SQLTree
5
+ class << self
6
+ attr_accessor :identifier_quote_field_char
7
+ end
8
+ self.identifier_quote_field_char = '`'
9
+ end
10
+
11
+ class SQLTree::Token
12
+ KEYWORDS << 'BINARY'
13
+ KEYWORDS << 'LIMIT'
14
+ KEYWORDS << 'OFFSET'
15
+ const_set('BINARY', Class.new(SQLTree::Token::Keyword))
16
+ const_set('LIMIT', Class.new(SQLTree::Token::Keyword))
17
+ const_set('OFFSET', Class.new(SQLTree::Token::Keyword))
18
+ end
19
+
20
+ class SQLTree::Tokenizer
21
+ def tokenize_quoted_string(&block) # :yields: SQLTree::Token::String
22
+ string = ''
23
+ until next_char.nil? || current_char == "'"
24
+ string << (current_char == "\\" ? instance_eval("%@\\#{next_char.gsub('@', '\@')}@") : current_char)
25
+ end
26
+ handle_token(SQLTree::Token::String.new(string), &block)
27
+ end
28
+ end
29
+
30
+ module SQLTree::Node
31
+ class Base
32
+ def quote_field_name(field_name)
33
+ "#{SQLTree.identifier_quote_field_char}#{field_name}#{SQLTree.identifier_quote_field_char}"
34
+ end
35
+ end
36
+
37
+ class SelectQuery < Base
38
+ child :offset
39
+
40
+ def to_sql(options = {})
41
+ raise "At least one SELECT expression is required" if self.select.empty?
42
+ sql = (self.distinct) ? "SELECT DISTINCT " : "SELECT "
43
+ sql << select.map { |s| s.to_sql(options) }.join(', ')
44
+ sql << " FROM " << from.map { |f| f.to_sql(options) }.join(', ') if from
45
+ sql << " WHERE " << where.to_sql(options) if where
46
+ sql << " GROUP BY " << group_by.map { |g| g.to_sql(options) }.join(', ') if group_by
47
+ sql << " ORDER BY " << order_by.map { |o| o.to_sql(options) }.join(', ') if order_by
48
+ sql << " HAVING " << having.to_sql(options) if having
49
+ sql << " LIMIT " << limit.map {|f| f.to_sql(options) }.join(', ') if limit
50
+ sql << " OFFSET " << offset.to_sql(options) if offset
51
+ return sql
52
+ end
53
+
54
+ def self.parse(tokens)
55
+ select_node = self.new
56
+ tokens.consume(SQLTree::Token::SELECT)
57
+
58
+ if SQLTree::Token::DISTINCT === tokens.peek
59
+ tokens.consume(SQLTree::Token::DISTINCT)
60
+ select_node.distinct = true
61
+ end
62
+
63
+ select_node.select = parse_list(tokens, SQLTree::Node::SelectDeclaration)
64
+ select_node.from = self.parse_from_clause(tokens) if SQLTree::Token::FROM === tokens.peek
65
+ select_node.where = self.parse_where_clause(tokens) if SQLTree::Token::WHERE === tokens.peek
66
+ if SQLTree::Token::GROUP === tokens.peek
67
+ select_node.group_by = self.parse_group_clause(tokens)
68
+ select_node.having = self.parse_having_clause(tokens) if SQLTree::Token::HAVING === tokens.peek
69
+ end
70
+ select_node.order_by = self.parse_order_clause(tokens) if SQLTree::Token::ORDER === tokens.peek
71
+ if SQLTree::Token::LIMIT === tokens.peek and list = self.parse_limit_clause(tokens)
72
+ select_node.offset = list.shift if list.size > 1
73
+ select_node.limit = list.shift
74
+ end
75
+ select_node.offset = self.parse_offset_clause(tokens) if SQLTree::Token::OFFSET === tokens.peek
76
+ return select_node
77
+ end
78
+
79
+ def self.parse_limit_clause(tokens)
80
+ tokens.consume(SQLTree::Token::LIMIT)
81
+ self.parse_list(tokens, SQLTree::Node::Expression)
82
+ end
83
+
84
+ def self.parse_offset_clause(tokens)
85
+ tokens.consume(SQLTree::Token::OFFSET)
86
+ Expression.parse(tokens)
87
+ end
88
+ end
89
+
90
+ class SubQuery < SelectQuery
91
+ def to_sql(options = {})
92
+ "("+super(options)+")"
93
+ end
94
+
95
+ def self.parse(tokens)
96
+ tokens.consume(SQLTree::Token::LPAREN)
97
+ select_node = super(tokens)
98
+ tokens.consume(SQLTree::Token::RPAREN)
99
+ return select_node
100
+ end
101
+ end
102
+
103
+ class TableReference < Base
104
+ def to_sql(options={})
105
+ sql = (SQLTree::Node::SubQuery === table) ? table.to_sql : quote_field_name(table)
106
+ sql << " AS " << quote_field_name(table_alias) if table_alias
107
+ return sql
108
+ end
109
+
110
+ def self.parse(tokens)
111
+ if SQLTree::Token::Identifier === tokens.peek
112
+ tokens.next
113
+ table_reference = self.new(tokens.current.literal)
114
+ if SQLTree::Token::AS === tokens.peek || SQLTree::Token::Identifier === tokens.peek
115
+ tokens.consume(SQLTree::Token::AS) if SQLTree::Token::AS === tokens.peek
116
+ table_reference.table_alias = tokens.next.literal
117
+ end
118
+ return table_reference
119
+ elsif SQLTree::Token::SELECT === tokens.peek(2)
120
+ table_reference = self.new(SQLTree::Node::SubQuery.parse(tokens))
121
+ if SQLTree::Token::AS === tokens.peek || SQLTree::Token::Identifier === tokens.peek
122
+ tokens.consume(SQLTree::Token::AS) if SQLTree::Token::AS === tokens.peek
123
+ table_reference.table_alias = tokens.next.literal
124
+ end
125
+ table_reference
126
+ else
127
+ raise SQLTree::Parser::UnexpectedToken.new(tokens.current)
128
+ end
129
+ end
130
+ end
131
+
132
+ class Expression < Base
133
+ class BinaryOperator < SQLTree::Node::Expression
134
+ TOKEN_PRECEDENCE[2] << SQLTree::Token::BETWEEN
135
+ silence_warnings do
136
+ TOKENS = TOKEN_PRECEDENCE.flatten
137
+ end
138
+
139
+ def self.parse_rhs(tokens, precedence, operator = nil)
140
+ if ['IN', 'NOT IN'].include?(operator)
141
+ if SQLTree::Token::SELECT === tokens.peek(2)
142
+ return SQLTree::Node::SubQuery.parse(tokens)
143
+ else
144
+ return List.parse(tokens)
145
+ end
146
+ elsif ['IS', 'IS NOT'].include?(operator)
147
+ tokens.consume(SQLTree::Token::NULL)
148
+ return SQLTree::Node::Expression::Value.new(nil)
149
+ elsif ['BETWEEN'].include?(operator)
150
+ expr = parse_atomic(tokens)
151
+ operator = parse_operator(tokens)
152
+ rhs = parse_rhs(tokens, precedence, operator)
153
+ expr = self.new(:operator => operator, :lhs => expr, :rhs => rhs)
154
+ return expr
155
+ else
156
+ return parse(tokens, precedence + 1)
157
+ end
158
+ end
159
+ end
160
+
161
+ class PrefixOperator < SQLTree::Node::Expression
162
+ TOKENS << SQLTree::Token::BINARY
163
+ end
164
+
165
+ class Field < Variable
166
+ def to_sql(options = {})
167
+ @table.nil? ? quote_field_name(@name) : quote_field_name(@table) + '.' + quote_field_name(@name)
168
+ end
169
+ end
170
+ end
171
+
172
+ class InsertQuery < Base
173
+
174
+ def to_sql(options = { })
175
+ sql = "INSERT INTO #{ table.to_sql(options)} "
176
+ sql << '(' + fields.map { |f| f.to_sql(options) }.join(', ') + ') ' if fields
177
+ sql << 'VALUES'
178
+ sql << values.map do |value|
179
+ ' (' + value.map { |v| v.to_sql(options) }.join(', ') + ')'
180
+ end.join(',')
181
+ sql
182
+ end
183
+
184
+ def self.parse_value_list(tokens)
185
+ values = []
186
+ tokens.consume(SQLTree::Token::VALUES)
187
+ tokens.consume(SQLTree::Token::LPAREN)
188
+ values << parse_list(tokens)
189
+ tokens.consume(SQLTree::Token::RPAREN)
190
+ while SQLTree::Token::COMMA === tokens.peek
191
+ tokens.consume(SQLTree::Token::COMMA)
192
+ tokens.consume(SQLTree::Token::LPAREN)
193
+ values << parse_list(tokens)
194
+ tokens.consume(SQLTree::Token::RPAREN)
195
+ end
196
+ return values
197
+ end
198
+ end
199
+ end
@@ -0,0 +1,5 @@
1
+ module ActiveRecord
2
+ module Turntable
3
+ VERSION = "1.0.0"
4
+ end
5
+ end
@@ -0,0 +1,2 @@
1
+ require 'active_record'
2
+ require 'active_record/turntable'
@@ -0,0 +1,14 @@
1
+ module ActiveRecord::Turntable
2
+ module Generators
3
+ class InstallGenerator < Rails::Generators::Base
4
+ source_root File.expand_path("../../../templates", __FILE__)
5
+
6
+ desc "Creates turntable configuration file (config/turntable.yml)"
7
+ class_option :orm
8
+
9
+ def copy_locale
10
+ copy_file "turntable.yml", "config/turntable.yml"
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,40 @@
1
+ #
2
+ # ActiveRecord::Turntable configuration file
3
+ #
4
+
5
+ development:
6
+ clusters:
7
+ user_cluster:
8
+ algorithm: range
9
+ shards:
10
+ - connection: user_shard_1
11
+ less_than: 100
12
+ - connection: user_shard_2
13
+ less_than: 200
14
+ - connection: user_shard_3
15
+ less_than: 300
16
+
17
+ test:
18
+ clusters:
19
+ user_cluster:
20
+ algorithm: range
21
+ shards:
22
+ - connection: user_shard_1
23
+ less_than: 20000
24
+ - connection: user_shard_2
25
+ less_than: 40000
26
+ - connection: user_shard_3
27
+ less_than: 10000000
28
+
29
+ production:
30
+ clusters:
31
+ user_cluster:
32
+ algorithm: range
33
+ shards:
34
+ - connection: user_shard_1
35
+ less_than: 20000
36
+ - connection: user_shard_2
37
+ less_than: 40000
38
+ - connection: user_shard_3
39
+ less_than: 10000000
40
+
@@ -0,0 +1,16 @@
1
+ # See http://help.github.com/ignore-files/ for more about ignoring files.
2
+ #
3
+ # If you find yourself ignoring temporary files generated by your text editor
4
+ # or operating system, you probably want to add a global ignore instead:
5
+ # git config --global core.excludesfile ~/.gitignore_global
6
+
7
+ # Ignore bundler config
8
+ /.bundle
9
+
10
+ # Ignore the default SQLite database.
11
+ /db/*.sqlite3
12
+ /db/schema*
13
+
14
+ # Ignore all logfiles and tempfiles.
15
+ /log/*.log
16
+ /tmp
@@ -0,0 +1,41 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gem 'rails', '3.2.2'
4
+
5
+ # Bundle edge Rails instead:
6
+ # gem 'rails', :git => 'git://github.com/rails/rails.git'
7
+
8
+ gem 'mysql2'
9
+
10
+ gem 'activerecord-turntable', '1.0.0'
11
+
12
+
13
+ # Gems used only for assets and not required
14
+ # in production environments by default.
15
+ group :assets do
16
+ gem 'sass-rails', '~> 3.2.3'
17
+ gem 'coffee-rails', '~> 3.2.1'
18
+
19
+ # See https://github.com/sstephenson/execjs#readme for more supported runtimes
20
+ # gem 'therubyracer'
21
+
22
+ gem 'uglifier', '>= 1.0.3'
23
+ end
24
+
25
+ gem 'jquery-rails'
26
+ gem 'pry-rails'
27
+
28
+ # To use ActiveModel has_secure_password
29
+ # gem 'bcrypt-ruby', '~> 3.0.0'
30
+
31
+ # To use Jbuilder templates for JSON
32
+ # gem 'jbuilder'
33
+
34
+ # Use unicorn as the app server
35
+ # gem 'unicorn'
36
+
37
+ # Deploy with Capistrano
38
+ # gem 'capistrano'
39
+
40
+ # To use debugger
41
+ # gem 'ruby-debug19', :require => 'ruby-debug'
@@ -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.