diff options
Diffstat (limited to 'railties/guides/source')
4 files changed, 267 insertions, 48 deletions
diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 15d24f9ac1..72ac8d2db9 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -675,7 +675,7 @@ The following is a list of the most commonly used methods. Please refer to the + h4(#working_with_validation_errors-errors). +errors+ -Returns an instance of the class +ActiveModel::Errors+ (which behaves like an ordered hash) containing all errors. Each key is the attribute name and the value is an array of strings with all errors. +Returns an instance of the class +ActiveModel::Errors+ containing all errors. Each key is the attribute name and the value is an array of strings with all errors. <ruby> class Person < ActiveRecord::Base diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index a55ed38d1b..ba92aedbd0 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -358,6 +358,7 @@ Here are a few things you should know to make efficient use of Active Record ass * Avoiding name collisions * Updating the schema * Controlling association scope +* Bi-directional associations h4. Controlling Caching @@ -501,6 +502,59 @@ module MyApplication end </ruby> +h4. Bi-directional Associations + +It's normal for associations to work in two directions, requiring declaration on two different models: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders +end + +class Order < ActiveRecord::Base + belongs_to :customer +end +</ruby> + +By default, Active Record doesn't know about the connection between these associations. This can lead to two copies of an object getting out of sync: + +<ruby> +c = Customer.first +o = c.orders.first +c.first_name == o.customer.first_name # => true +c.first_name = 'Manny' +c.first_name == o.customer.first_name # => false +</ruby> + +This happens because c and o.customer are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the +:inverse_of+ option so that you can inform it of these relations: + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :inverse_of => :customer +end + +class Order < ActiveRecord::Base + belongs_to :customer, :inverse_of => :orders +end +</ruby> + +With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient: + +<ruby> +c = Customer.first +o = c.orders.first +c.first_name == o.customer.first_name # => true +c.first_name = 'Manny' +c.first_name == o.customer.first_name # => true +</ruby> + +There are a few limitations to +inverse_of+ support: + +* They do not work with <tt>:through</tt> associations. +* They do not work with <tt>:polymorphic</tt> associations. +* They do not work with <tt>:as</tt> associations. +* For +belongs_to+ associations, +has_many+ inverse associations are ignored. + h3. Detailed Association Reference The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association. @@ -594,6 +648,7 @@ The +belongs_to+ association supports these options: * +:dependent+ * +:foreign_key+ * +:include+ +* +:inverse_of+ * +:polymorphic+ * +:readonly+ * +:select+ @@ -720,6 +775,20 @@ end NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed. +h6(#belongs_to-inverse_of). +:inverse_of+ + +The +:inverse_of+ option specifies the name of the +has_many+ or +has_one+ association that is the inverse of this association. Does not work in combination with the +:polymorphic+ options. + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :inverse_of => :customer +end + +class Order < ActiveRecord::Base + belongs_to :customer, :inverse_of => :orders +end +</ruby> + h6(#belongs_to-polymorphic). +:polymorphic+ Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>. @@ -859,6 +928,7 @@ The +has_one+ association supports these options: * +:dependent+ * +:foreign_key+ * +:include+ +* +:inverse_of+ * +:order+ * +:primary_key+ * +:readonly+ @@ -899,6 +969,9 @@ end h6(#has_one-dependent). +:dependent+ If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+. +If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised. + +NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config. h6(#has_one-foreign_key). +:foreign_key+ @@ -948,6 +1021,20 @@ class Representative < ActiveRecord::Base end </ruby> +h6(#has_one-inverse_of). +:inverse_of+ + +The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options. + +<ruby> +class Supplier < ActiveRecord::Base + has_one :account, :inverse_of => :supplier +end + +class Account < ActiveRecord::Base + belongs_to :supplier, :inverse_of => :account +end +</ruby> + h6(#has_one-order). +:order+ The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed. @@ -1177,6 +1264,7 @@ The +has_many+ association supports these options: * +:foreign_key+ * +:group+ * +:include+ +* +:inverse_of+ * +:limit+ * +:offset+ * +:order+ @@ -1247,6 +1335,9 @@ NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL h6(#has_many-dependent). +:dependent+ If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+. +If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised. + +NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config. NOTE: This option is ignored when you use the +:through+ option on the association. @@ -1316,6 +1407,20 @@ class LineItem < ActiveRecord::Base end </ruby> +h6(#has_many-inverse_of). +:inverse_of+ + +The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options. + +<ruby> +class Customer < ActiveRecord::Base + has_many :orders, :inverse_of => :customer +end + +class Order < ActiveRecord::Base + belongs_to :customer, :inverse_of => :orders +end +</ruby> + h6(#has_many-limit). +:limit+ The +:limit+ option lets you restrict the total number of objects that will be fetched through an association. diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index 694b36bea1..e6058e7581 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -12,33 +12,43 @@ endprologue. h3. What are engines? -Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the +Rails::Application+ class inheriting from +Rails::Engine+. Therefore, engines and applications share common functionality but are at the same time two separate beasts. Engines and applications also share a common structure, as you'll see throughout this guide. +Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the +Rails::Application+ class inheriting a lot of its behaviour from +Rails::Engine+. -Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator. +Therefore, engines and applications can be thought of almost the same thing, just with very minor differences, as you'll see throughout this guide. Engines and applications also share a common structure. -The engine that will be generated for this guide will be called "blorgh". The engine will provide blogging functionality to its host applications, allowing for new posts and comments to be created. For now, you will be working solely within the engine itself and in later sections you'll see how to hook it into an application. +Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator. The difference being that an engine is considered a "full plugin" by Rails -- as indicated by the +--full+ option that's passed to the generator command -- but this guide will refer to them simply as "engines" throughout. An engine *can* be a plugin, and a plugin *can* be an engine. + +The engine that will be created in this guide will be called "blorgh". The engine will provide blogging functionality to its host applications, allowing for new posts and comments to be created. At the beginning of this guide, you will be working solely within the engine itself, but in later sections you'll see how to hook it into an application. Engines can also be isolated from their host applications. This means that an application is able to have a path provided by a routing helper such as +posts_path+ and use an engine also that provides a path also called +posts_path+, and the two would not clash. Along with this, controllers, models and table names are also namespaced. You'll see how to do this later in this guide. -To see demonstrations of other engines, check out "Devise":https://github.com/plataformatec/devise, an engine that provides authentication for its parent applications, or "Forem":https://github.com/radar/forem, an engine that provides forum functionality. +It's important to keep in mind at all times that the application should *always* take precedence over its engines. An application is the object that has final say in what goes on in the universe (with the universe being the application's environment) where the engine should only be enhancing it, rather than changing it drastically. + +To see demonstrations of other engines, check out "Devise":https://github.com/plataformatec/devise, an engine that provides authentication for its parent applications, or "Forem":https://github.com/radar/forem, an engine that provides forum functionality. There's also "Spree":https://github.com/spree/spree which provides an e-commerce platform, and "RefineryCMS":https://github.com/resolve/refinerycms, a CMS engine. Finally, engines would not have be possible without the work of James Adam, Piotr Sarnacki, the Rails Core Team, and a number of other people. If you ever meet them, don't forget to say thanks! h3. Generating an engine -To generate an engine with Rails 3.1, you will need to run the plugin generator and pass it the +--mountable+ option. To generate the beginnings of the "blorgh" engine you will need to run this command in a terminal: +To generate an engine with Rails 3.1, you will need to run the plugin generator and pass it the +--full+ and +--mountable+ options. To generate the beginnings of the "blorgh" engine you will need to run this command in a terminal: <shell> -$ rails plugin new blorgh --mountable +$ rails plugin new blorgh --full --mountable </shell> -The +--mountable+ option tells the plugin generator that you want to create an engine (which is a mountable plugin, hence the option name), creating the basic directory structure of an engine by providing things such as the foundations of an +app+ folder, as well a +config/routes.rb+ file. This generator also provides a file at +lib/blorgh/engine.rb+ which is identical in function to an application's +config/application.rb+ file. +The +--full+ option tells the plugin generator that you want to create an engine (which is a mountable plugin, hence the option name), creating the basic directory structure of an engine by providing things such as the foundations of an +app+ folder, as well a +config/routes.rb+ file. This generator also provides a file at +lib/blorgh/engine.rb+ which is identical in function to an application's +config/application.rb+ file. + +The +--mountable+ option tells the generator to mount the engine inside the dummy testing application located at +test/dummy+ inside the engine. It does this by placing this line in to the dummy application's +config/routes.rb+ file, located at +test/dummy/config/routes.rb+ inside the engine: + +<ruby> +mount Blorgh::Engine, :at => "blorgh" +</ruby> h4. Inside an engine h5. Critical files -At the root of the engine's directory, lives a +blorgh.gemspec+ file. When you include the engine into the application later on, you will do so with this line in a Rails application's +Gemfile+: +At the root of this brand new engine's directory, lives a +blorgh.gemspec+ file. When you include the engine into the application later on, you will do so with this line in a Rails application's +Gemfile+: <ruby> gem 'blorgh', :path => "vendor/engines/blorgh" @@ -53,6 +63,8 @@ module Blorgh end </ruby> +TIP: Some engines choose to use this file to put global configuration options for their engine. It's a relatively good idea, and so if you're wanting offer configuration options, the file where your engine's +module+ is defined is perfect for that. Place the methods inside the module and you'll be good to go. + Within +lib/blorgh/engine.rb+ is the base class for the engine: <ruby> @@ -63,23 +75,39 @@ module Blorgh end </ruby> -By inheriting from the +Rails::Engine+ class, this engine gains all the functionality it needs, such as being able to serve requests to its controllers. +By inheriting from the +Rails::Engine+ class, this gem notifies Rails that there's an engine at the specified path, and will correctly mount the engine inside the application, performing tasks such as adding the +app+ directory of the engine to the load path for models, mailers, controllers and views. + +The +isolate_namespace+ method here deserves special notice. This call is responsible for isolating the controllers, models, routes and other things into their own namespace, away from similar components inside hte application. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption, or that important engine components could be overriden by similarly named things within the application. + +NOTE: It is *highly* recommended that the +isolate_namespace+ line be left within the +Engine+ class definition. Without it, classes generated in an engine *may* conflict with an application. + +What this isolation of the namespace means is that a model generated by a call to +rails g model+ such as +rails g model post+ wouldn't be called +Post+, but instead be namespaced and called +Blorgh::Post+. In addition to this, the table for the model is namespaced, becoming +blorgh_posts+, rather than simply +posts+. Similar to the model namespacing, a controller called +PostsController+ would be +Blorgh::Postscontroller+ and the views for that controller would not be at +app/views/posts+, but rather +app/views/blorgh/posts+. Mailers would be namespaced as well. -The +isolate_namespace+ method here deserves special notice. This call is responsible for isolating the controllers, models, routes and other things into their own namespace. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption. It is recommended that this line be left within this file. +Finally, routes will also be isolated within the engine. This is one of the most important parts about namespacing, and is discussed later in the "Routes":#routes section of this guide. h5. +app+ directory -Inside the +app+ directory there lives the standard +assets+, +controllers+, +helpers+, +mailers+, +models+ and +views+ directories that you should be familiar with from an application. The +helpers+, +mailers+ and +models+ directories are empty and so aren't described in this section. We'll look more into models in a future section. +Inside the +app+ directory there is the standard +assets+, +controllers+, +helpers+, +mailers+, +models+ and +views+ directories that you should be familiar with from an application. The +helpers+, +mailers+ and +models+ directories are empty and so aren't described in this section. We'll look more into models in a future section, when we're writing the engine. Within the +app/assets+ directory, there is the +images+, +javascripts+ and +stylesheets+ directories which, again, you should be familiar with due to their similarities of an application. One difference here however is that each directory contains a sub-directory with the engine name. Because this engine is going to be namespaced, its assets should be too. Within the +app/controllers+ directory there is a +blorgh+ directory and inside that a file called +application_controller.rb+. This file will provide any common functionality for the controllers of the engine. The +blorgh+ directory is where the other controllers for the engine will go. By placing them within this namespaced directory, you prevent them from possibly clashing with identically-named controllers within other engines or even within the application. +NOTE: The +ApplicationController+ class is called as such inside an engine -- rather than +EngineController+ -- mainly due to that if you consider that an engine is really just a mini-application, it makes sense. You should also be able to convert an application to an engine with relatively little pain, and this is just one of the ways to make that process easier, albeit however so slightly. + Lastly, the +app/views+ directory contains a +layouts+ folder which contains file at +blorgh/application.html.erb+ which allows you to specify a layout for the engine. If this engine is to be used as a stand-alone engine, then you would add any customization to its layout in this file, rather than the applications +app/views/layouts/application.html.erb+ file. +If you don't want to force a layout on to users of the engine, then you can delete this file and reference a different layout in the controllers of your engine. + h5. +script+ directory -This directory contains one file, +script/rails+, which allows you to use the +rails+ sub-commands and generators just like you would within an application. This means that you will very easily be able to generate new controllers and models for this engine. +This directory contains one file, +script/rails+, which enables you to use the +rails+ sub-commands and generators just like you would within an application. This means that you will very easily be able to generate new controllers and models for this engine by running commands like this: + +<shell> +rails g model +</shell> + +Keeping in mind, of course, that anything generated with these commands inside an engine that has +isolate_namespace+ inside the Engine class will be namespaced. h5. +test+ directory @@ -92,9 +120,9 @@ Rails.application.routes.draw do end </ruby> -This line mounts the engine at the path of +/blorgh+, which will make it accessible through the application only at that path. We will look more into mounting an engine after some features have been developed. +This line mounts the engine at the path of +/blorgh+, which will make it accessible through the application only at that path. -Also in the test directory is the +test/integration+ directory, where integration tests for the engine should be placed. +Also in the test directory is the +test/integration+ directory, where integration tests for the engine should be placed. Other directories can be created in the +test+ directory also. For example, you may wish to create a +test/unit+ directory for your unit tests. h3. Providing engine functionality @@ -142,11 +170,11 @@ invoke css create app/assets/stylesheets/scaffold.css </shell> -The first thing that the scaffold generator does is invoke the +active_record+ generator, which generates a migration and a model for the resource. Note here, however, that the migration is called +create_blorgh_posts+ rather than the usual +create_posts+. This is due to the +isolate_namespace+ method called in the +Blorgh::Engine+ class's definition. The model here is also namespaced, being placed at +app/models/blorgh/post.rb+ rather than +app/models/post.rb+. +The first thing that the scaffold generator does is invoke the +active_record+ generator, which generates a migration and a model for the resource. Note here, however, that the migration is called +create_blorgh_posts+ rather than the usual +create_posts+. This is due to the +isolate_namespace+ method called in the +Blorgh::Engine+ class's definition. The model here is also namespaced, being placed at +app/models/blorgh/post.rb+ rather than +app/models/post.rb+ due to the +isolate_namespace+ call within the +Engine+ class. Next, the +test_unit+ generator is invoked for this model, generating a unit test at +test/unit/blorgh/post_test.rb+ (rather than +test/unit/post_test.rb+) and a fixture at +test/fixtures/blorgh/posts.yml+ (rather than +test/fixtures/posts.yml+). -After that, a line for the resource is inserted into the +config/routes.rb+ file for the engine. This line is simply +resources :posts+, turning the +config/routes.rb+ file into this: +After that, a line for the resource is inserted into the +config/routes.rb+ file for the engine. This line is simply +resources :posts+, turning the +config/routes.rb+ file for the engine into this: <ruby> Blorgh::Engine.routes.draw do @@ -155,11 +183,11 @@ Blorgh::Engine.routes.draw do end </ruby> -Note here that the routes are drawn upon the +Blorgh::Engine+ object rather than the +YourApp::Application+ class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the "test directory":#test-directory section. +Note here that the routes are drawn upon the +Blorgh::Engine+ object rather than the +YourApp::Application+ class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the "test directory":#test-directory section. This is also what causes the engine's routes to be isolated from those routes that are within the application. This is discussed further in the "Routes":#routes section of this guide. Next, the +scaffold_controller+ generator is invoked, generating a controlled called +Blorgh::PostsController+ (at +app/controllers/blorgh/posts_controller.rb+) and its related views at +app/views/blorgh/posts+. This generator also generates a functional test for the controller (+test/functional/blorgh/posts_controller_test.rb+) and a helper (+app/helpers/blorgh/posts_controller.rb+). -Everything this generator has generated is neatly namespaced. The controller's class is defined within the +Blorgh+ module: +Everything this generator has created is neatly namespaced. The controller's class is defined within the +Blorgh+ module: <ruby> module Blorgh @@ -171,7 +199,7 @@ end NOTE: The +ApplicationController+ class being inherited from here is the +Blorgh::ApplicationController+, not an application's +ApplicationController+. -The helper is also namespaced: +The helper inside +app/helpers/blorgh/posts_helper.rb+ is also namespaced: <ruby> module Blorgh @@ -210,7 +238,7 @@ One final thing is that the +posts+ resource for this engine should be the root root :to => "posts#index" </ruby> -Now people will only need to go to the root of the engine to see all the posts, rather than visiting +/posts+. +Now people will only need to go to the root of the engine to see all the posts, rather than visiting +/posts+. This means that instead of +http://localhost:3000/blorgh/posts+, you only need to go to +http://localhost:3000/blorgh+ now. h4. Generating a comments resource @@ -258,7 +286,7 @@ module Blorgh end </ruby> -Because the +has_many+ is defined inside a class that is inside the +Blorgh+ module, Rails will know that you want to use the +Blorgh::Comment+ model for these objects. +NOTE: Because the +has_many+ is defined inside a class that is inside the +Blorgh+ module, Rails will know that you want to use the +Blorgh::Comment+ model for these objects, so there's no need to specify that using the +:class_name+ option here. Next, there needs to be a form so that comments can be created on a post. To add this, put this line underneath the call to +render @post.comments+ in +app/views/blorgh/posts/show.html.erb+: @@ -279,7 +307,7 @@ Next, the partial that this line will render needs to exist. Create a new direct <% end %> </erb> -This form, when submitted, is going to attempt to post to a route of +posts/:post_id/comments+ within the engine. This route doesn't exist at the moment, but can be created by changing the +resources :posts+ line inside +config/routes.rb+ into these lines: +When this form is submitted, it is going to attempt to perform a +POST+ request to a route of +/posts/:post_id/comments+ within the engine. This route doesn't exist at the moment, but can be created by changing the +resources :posts+ line inside +config/routes.rb+ into these lines: <ruby> resources :posts do @@ -287,7 +315,9 @@ resources :posts do end </ruby> -The route now will exist, but the controller that this route goes to does not. To create it, run this command: +This creates a nested route for the comments, which is what the form requires. + +The route now exists, but the controller that this route goes to does not. To create it, run this command: <shell> $ rails g controller comments @@ -378,10 +408,10 @@ As described earlier, by placing the gem in the +Gemfile+ it will be loaded when To make the engine's functionality accessible from within an application, it needs to be mounted in that application's +config/routes.rb+ file: <ruby> -mount Blorgh::Engine, :at => "blog" +mount Blorgh::Engine, :at => "/blog" </ruby> -This line will mount the engine at +blog+ in the application. Making it accessible at +http://localhost:3000/blog+ when the application runs with +rails s+. +This line will mount the engine at +/blog+ in the application. Making it accessible at +http://localhost:3000/blog+ when the application runs with +rails server+. NOTE: Other engines, such as Devise, handle this a little differently by making you specify custom helpers such as +devise_for+ in the routes. These helpers do exactly the same thing, mounting pieces of the engines's functionality at a pre-defined path which may be customizable. @@ -393,6 +423,12 @@ The engine contains migrations for the +blorgh_posts+ and +blorgh_comments+ tabl $ rake blorgh:install:migrations </shell> +If you have multiple engines that need migrations copied over, use +railties:install:migrations+ instead: + +<shell> +$ rake railties:install:migrations +</shell> + This command, when run for the first time will copy over all the migrations from the engine. When run the next time, it will only copy over migrations that haven't been copied over already. The first run for this command will output something such as this: <shell> @@ -410,7 +446,7 @@ When an engine is created, it may want to use specific classes from an applicati Usually, an application would have a +User+ class that would provide the objects that would represent the posts' and comments' authors, but there could be a case where the application calls this class something different, such as +Person+. It's because of this reason that the engine should not hardcode the associations to be exactly for a +User+ class, but should allow for some flexibility around what the class is called. -To keep it simple in this case, the application will have a class called +User+ which will represent the users of the application. It can be generated using this command: +To keep it simple in this case, the application will have a class called +User+ which will represent the users of the application. It can be generated using this command inside the application: <shell> rails g model user name:string @@ -418,7 +454,7 @@ rails g model user name:string The +rake db:migrate+ command needs to be run here to ensure that our application has the +users+ table for future use. -Also to keep it simple, the posts form will have a new text field called +author_name_+ where users can elect to put their name. The engine will then take this name and create a new +User+ object from it or find one that already has that name, and then associate the post with it. +Also, to keep it simple, the posts form will have a new text field called +author_name+ where users can elect to put their name. The engine will then take this name and create a new +User+ object from it or find one that already has that name, and then associate the post with it. First, the +author_name+ text field needs to be added to the +app/views/blorgh/posts/_form.html.erb+ partial inside the engine. This can be added above the +title+ field with this code: @@ -486,8 +522,6 @@ Finally, the author's name should be displayed on the post's page. Add this code </p> </erb> -WARNING: For posts created previously, this will break the +show+ page for them. We recommend deleting these posts and starting again, or manually assigning an author using +rails c+. - By outputting +@post.author+ using the +<%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly: <text> @@ -532,7 +566,23 @@ The +set_author+ method also located in this class should also use this class: self.author = Blorgh.user_class.constantize.find_or_create_by_name(author_name) </ruby> -To set this configuration setting within the application, an initializer should be used. By using an initializer, the configuration will be set up before the application starts and makes references to the classes of the engine which may depend on this configuration setting existing. +To save having to call +constantize+ on the +user_class+ result all the time, you could instead just override the +user_class+ getter method inside the +Blorgh+ module in the +lib/blorgh.rb+ file to always call +constantize+ on the saved value before returning the result: + +<ruby> + def self.user_class + @@user_class.constantize + end +</ruby> + +This would then turn the above code for +self.author=+ into this: + +<ruby> +self.author = Blorgh.user_class.find_or_create_by_name(author_name) +</ruby> + +Resulting in something a little shorter, and more implicit in its behaviour. The +user_class+ method should always return a +Class+ object. + +To set this configuration setting within the application, an initializer should be used. By using an initializer, the configuration will be set up before the application starts and calls the engine's models which may depend on this configuration setting existing. Create a new initializer at +config/initializers/blorgh.rb+ inside the application where the +blorgh+ engine is installed and put this content in it: @@ -544,23 +594,45 @@ WARNING: It's very important here to use the +String+ version of the class, rath Go ahead and try to create a new post. You will see that it works exactly in the same way as before, except this time the engine is using the configuration setting in +config/initializers/blorgh.rb+ to learn what the class is. -There are now no strict dependencies on what the class is, only what the class's API must be. The engine simply requires this class to define a +find_or_create_by_name+ method which returns an object of that class to be associated with a post when it's created. +There are now no strict dependencies on what the class is, only what the class's API must be. The engine simply requires this class to define a +find_or_create_by_name+ method which returns an object of that class to be associated with a post when it's created. This object, of course, should have some sort of identifier by which it can be referenced. h5. General engine configuration Within an engine, there may come a time where you wish to use things such as initializers, internationalization or other configuration options. The great news is that these things are entirely possible because a Rails engine shares much the same functionality as a Rails application. In fact, a Rails application's functionality is actually a superset of what is provided by engines! -If you wish to use initializers (code that should run before the engine is loaded), the best place for them is the +config/initializers+ folder. This directory's functionality is explained in the "Initializers section":http://guides.rubyonrails.org/configuring.html#initializers of the Configuring guide. +If you wish to use an initializer -- code that should run before the engine is loaded -- the place for it is the +config/initializers+ folder. This directory's functionality is explained in the "Initializers section":http://guides.rubyonrails.org/configuring.html#initializers of the Configuring guide, and works precisely the same way as the +config/initializers+ directory inside an application. Same goes for if you want to use a standard initializer. For locales, simply place the locale files in the +config/locales+ directory, just like you would in an application. -h3. Extending engine functionality +h3. Testing an engine + +When an engine is generated there is a smaller dummy application created inside it at +test/dummy+. This application is used as a mounting point for the engine to make testing the engine extremely simple. You may extend this application by generating controllers, models or views from within the directory, and then use those to test your engine. + +The +test+ directory should be treated like a typical Rails testing environment, allowing for unit, functional and integration tests. + +h4. Functional tests + +A matter worth taking into consideration when writing functional tests is that the tests are going to be running on an application -- the +test/dummy+ application -- rather than your engine. This is due to the setup of the testing environment; an engine needs an application as a host for testing its main functionality, especially controllers. This means that if you were to make a typical +GET+ to a controller in a controller's functional test like this: + +<ruby> +get :index +</ruby> + +It may not function correctly. This is because the application doesn't know how to route these requests to the engine unless you explicitly tell it *how*. To do this, you must pass the +:use_route+ option (as a parameter) on these requests also: + +<ruby> +get :index, :use_route => :blorgh +</ruby> + +This tells the application that you still want to perform a +GET+ request to the +index+ action of this controller, just that you want to use the engine's route to get there, rather than the application. + +h3. Improving engine functionality This section looks at overriding or adding functionality to the views, controllers and models provided by an engine. h4. Overriding views -When Rails looks for a view to render, it will first look in the +app/views+ directory of the application. If it cannot find the view there, then it will check in the +app/views+ directories of all engines which have this directory. +When Rails looks for a view to render, it will first look in the +app/views+ directory of the application. If it cannot find the view there, then it will check in the +app/views+ directories of all engines which have this directory. In the +blorgh+ engine, there is a currently a file at +app/views/blorgh/posts/index.html.erb+. When the engine is asked to render the view for +Blorgh::PostsController+'s +index+ action, it will first see if it can find it at +app/views/blorgh/posts/index.html.erb+ within the application and then if it cannot it will look inside the engine. @@ -583,36 +655,78 @@ Rather than looking like the default scaffold, the page will now look like this: !images/engines_post_override.png(Engine scaffold overriden)! -h4. Controllers +h4. Routes -TODO: Explain how to extend a controller. -IDEA: I like Devise's +devise :controllers => { "sessions" => "sessions" }+ idea. Perhaps we could incorporate that into the guide? +Routes inside an engine are, by default, isolated from the application. This is done by the +isolate_namespace+ call inside the +Engine+ class. This essentially means that the application and its engines can have identically named routes, and that they will not clash. -h4. Models +Routes inside an engine are drawn on the +Engine+ class within +config/routes.rb+, like this: -TODO: Explain how to extend models provided by an engine. +<ruby> + Blorgh::Engine.routes.draw do + resources :posts + end +</ruby> -h4. Routes +By having isolated routes such as this, if you wish to link to an area of an engine from within an application, you will need to use the engine's routing proxy method. Calls to normal routing methods such as +posts_path+ may end up going to undesired locations if both the application and the engine both have such a helper defined. -Within the application, you may wish to link to some area within the engine. Due to the fact that the engine's routes are isolated (by the +isolate_namespace+ call within the +lib/blorgh/engine.rb+ file), you will need to prefix these routes with the engine name. This means rather than having something such as: +For instance, the following example would go to the application's +posts_path+ if that template was rendered from the application, or the engine's +posts_path+ if it was rendered from the engine: <erb> <%= link_to "Blog posts", posts_path %> </erb> -It needs to be written as: +To make this route always use the engine's +posts_path+ routing helper method, we must call the method on the routing proxy method that shares the same name as the engine. <erb> <%= link_to "Blog posts", blorgh.posts_path %> </erb> -This allows for the engine _and_ the application to both have a +posts_path+ routing helper and to not interfere with each other. You may also reference another engine's routes from inside an engine using this same syntax. - If you wish to reference the application inside the engine in a similar way, use the +main_app+ helper: <erb> <%= link_to "Home", main_app.root_path %> </erb> -TODO: Mention how to use assets within an engine? -TODO: Mention how to depend on external gems, like RedCarpet. +If you were to use this inside an engine, it would *always* go to the application's root. If you were to leave off the +main_app+ "routing proxy" method call, it could potentially go to the engine's or application's root, depending on where it was called from. + +If a template is rendered from within an engine and it's attempting to use one of the application's routing helper methods, it may result in an undefined method call. If you encounter such an issue, ensure that you're not attempting to call the application's routing methods without the +main_app+ prefix from within the engine. + +h4. Assets + +Assets within an engine work in an identical way to a full application. Because the engine class inherits from +Rails::Engine+, the application will know to look up in the engine's +app/assets+ directory for potential assets. + +Much like all the other components of an engine, the assets should also be namespaced. This means if you have an asset called +style.css+, it should be placed at +app/assets/stylesheets/[engine name]/style.css+, rather than +app/assets/stylesheets/style.css+. If this asset wasn't namespaced, then there is a possibility that the host application could have an asset named identically, in which case the application's asset would take precedence and the engine's one would be all but ignored. + +Imagine that you did have an asset located at +app/assets/stylesheets/blorgh/style.css+ To include this asset inside an application, just use +stylesheet_link_tag+ and reference the asset as if it were inside the engine: + +<erb> +<%= stylesheet_link_tag "blorgh/style.css" %> +</erb> + +You can also specify these assets as dependencies of other assets using the Asset Pipeline require statements in processed files: + +<css> +/* + *= require blorgh/style +*/ +</css> + +For more information, read the "Asset Pipeline guide":http://guides.rubyonrails.org/asset_pipeline.html + +h4. Other gem dependencies + +Gem dependencies inside an engine should be specified inside the +.gemspec+ file that's at the root of the engine. The reason for this is because the engine may be installed as a gem. If dependencies were to be specified inside the +Gemfile+, these would not be recognised by a traditional gem install and so they would not be installed, causing the engine to malfunction. + +To specify a dependency that should be installed with the engine during a traditional +gem install+, specify it inside the +Gem::Specification+ block inside the +.gemspec+ file in the engine: + +<ruby> +s.add_dependency "moo" +</ruby> + +To specify a dependency that should only be installed as a development dependency of the application, specify it like this: + +<ruby> +s.add_development_dependency "moo" +</ruby> + +Both kinds of dependencies will be installed when +bundle install+ is run inside the application. The development dependencies for the gem will only be used when the tests for the engine are running. diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 6ac9645917..be352cfe3d 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -1188,7 +1188,7 @@ You can also specify a second partial to be rendered between instances of the ma h5. Spacer Templates <erb> -<%= render @products, :spacer_template => "product_ruler" %> +<%= render :partial => @products, :spacer_template => "product_ruler" %> </erb> Rails will render the +_product_ruler+ partial (with no data passed in to it) between each pair of +_product+ partials. |