Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Revised Rails Engine Patterns for Montreal.rb meetup Oct 16, 2012


Published on

  • Be the first to comment

Revised Rails Engine Patterns for Montreal.rb meetup Oct 16, 2012

  1. 1. Rails Engine Patterns Andy Maleh Software Engineer for Groupon (Oct 2011 - Oct 2012) Former Senior Consultant for Obtiva
  2. 2. Problem Difficulty reusing functionality cutting across: Models Views Controllers Assets (JS, CSS, Images) Duplication across all web application layers.
  3. 3. Courtesy of © 2002-2011 National Collegiate Scouting Association - All Rights Reserved
  4. 4. Solution Break common behavior into Rails Engines Customize models/controllers/helpers in each project where needed by reopening classes Customize Rails views in each project as needed by overriding templates Link to Rails Engines in Gemfile via Git repo
  5. 5. Example
  6. 6. Courtesy of © 2002-2011 National Collegiate Scouting Association - All Rights Reserved
  7. 7. Courtesy of © 2002-2011 National Collegiate Scouting Association - All Rights Reserved
  8. 8. What is a Rails Engine? Ruby Gem + MVC stack elements
  9. 9. What is a Rails Engine? Rails Engines let applications reuse: Models / Views / Controllers / Helpers Assets (JS, CSS, Images) Routes Rake tasks Generators
  10. 10. What is a Rails Engine? Rails Engines let applications reuse: Initializers RSpec / Cucumber Rack application with middleware stack Migrations and seed data Libraries
  11. 11. Engine Definition An engine structure is similar to a Rails app having app, config, lib, spec, features, etc… lib/engine_name.rb (engine loader) lib/engine_name/engine.rb (engine class) To reuse engine, generate gemspec (using “Jeweler or Gemcutter”)
  12. 12. lib/engine_name.rb
  13. 13. lib/engine_name/engine.rb
  14. 14. Isolated Engines To avoid Ruby namespace clash with Models/Helpers/Controllers, you can define an isolated (namespaced) engine. Add “isolate_namespace MyEngine” to engine class body For more details, go to Engine.html
  15. 15. Engine Consumption Reference engine via Gemfile as a Ruby gem or Git repo hosted gemified project:Courtesy of © 2002-2011 National Collegiate Scouting Association - All Rights Reserved
  16. 16. Engine Consumption To avoid frequent updates of ref (outsider advice):Courtesy of © 2002-2011 National Collegiate Scouting Association - All Rights Reserved
  17. 17. Load OrderTypically Rails app files load first before Enginefiles.Strongly recommended to reverse so thatengine’s code is customizable in app
  18. 18. Load OrderReversing load order can happen in one of twoways: Patching “active_support/dependencies.rb” in Rails 3.1- (see next slide) Adjusting railties_order in Rails 3.2+
  19. 19. Engine Configuration Engines can be configured to customize rack middleware, load paths, generators, and Rails component paths. More details at: http :// Engine.html
  20. 20. View and AssetCustomizationEngine View and Asset presentation can becustomized by redefining files in Rails App Customizations completely override files in Engine Examples of customizable View and Asset files: ERB/Haml JS CSS Images
  21. 21. Ruby Code CustomizationModel/Helper/Controller behavior can becustomized be redefining .rb files in Rails App Customizations get mixed in with files in Engine This allows: Adding new methods/behavior Replacing existing methods Extending existing methods (alias_method_chain)
  22. 22. Ruby CodeCustomization Example
  23. 23. Ruby CodeCustomization Example
  24. 24. ViewCustomization Example
  25. 25. ViewCustomization Example
  26. 26. Recommended EngineCode Management• Each Engine lives in own Repo independent of Rails App• Each Engine has its own Gem dependencies (Gemfile)• Engines preferably share the same Ruby version as Rails App
  27. 27. Typical DevelopmentProcess1.Make changes in engine, rake, and commit obtaining a new GIT ref2.Update Gemfile in app with new git ref, run “bundle install” (getting ride of symlink)3.Rake and commit changes in app.4.If more changes in engine are needed go back to step 1
  28. 28. Improved DevelopmentProcess1. Work in app and engine until done WITHOUT running “bundle install”2. Rake and commit changes in engine obtaining a new git ref3. Update Gemfile in app with git ref, run “bundle install”4. Rake and commit changes in app
  29. 29. Engines Reuse Engines Rails engines can reuse other Rails engines
  30. 30. Engines Reuse EnginesWhen multiple levels of depth are involved,commit repos and update Gemfile from thebottom up Example: Engine 2 => Engine 1 => App1. Commit in Engine 22. Update Gemfile in Engine 1 and commit3. Update Gemfile in App and commit
  31. 31. Rails Engine Patterns Goals: Keep engine code agnostic of app customizations Prevent bi-directional coupling to simplify reasoning about code Avoid app dependent conditionals to improve code maintainability
  32. 32. Pattern - Common DomainProblem: Multiple Rails Apps need to share a basicdomain model including default CRUD andpresentation behaviorExample: need to reuse address model and form entrybehavior
  33. 33. Pattern - Common Domain Solution: In engine, include basic domain models (base behavior, common associations) with their views, CRUD controllers, and routes. In each app, define domain model specialized behavior, extra associations, and custom views Make sure routes are declared with MyEngine::Engine.routes.draw (not Rails App name)
  34. 34. Pattern - Common DomainExample: address.rb, addresses_controller.rb,address route, and _address.html.erb
  35. 35. Pattern - Expose Helper Problem: need to customize presentation logic for a view in one app only, but keep the same logic in others Example: One App needs to hide address1 and county for non- government users. Other Apps wants to keep the fields displayed. You might start by overriding view, but then realize it is duplicating many elements just to hide a couple fields.
  36. 36. Pattern - Expose Helper Solution: In Engine, extract helper logic that needs customization into its own helper. In App, redefine that new helper with customizations.
  37. 37. Pattern - Expose Helper(view in Engine)
  38. 38. Pattern - Expose Helper(trying to customize view in App)
  39. 39. Pattern - Expose Helper Remove custom view from App Use requires_extended_address? helper in Engine wherever the App used government_user? In Engine, define requires_extended_address? to return true In App, define requires_extended_address? to return government_user?
  40. 40. Pattern - Expose Helper(view + helper in Engine)
  41. 41. Pattern - Expose Partial Problem: need to have different customizations in one part of the view in multiple apps Example: Address form One App needs an extra neighborhood field Another App needs an extra region field
  42. 42. Pattern - Expose Partial Example App 1:
  43. 43. Pattern - Expose Partial Example App 2:
  44. 44. Pattern - Expose Partial Solution: In Engine, extract view part that needs customization as a partial. In App, redefine that partial with customizations.
  45. 45. Pattern - Expose Partial Example: Define _address_extra_fields partial with empty content in Engine Redefine _address_extra_fields in Apps needing extra fields
  46. 46. Pattern - Extension Point Problem: multiple Apps need to contribute data to a View in different places Example: multiple Apps need to add custom Rows in different spots of a List that comes from an Engine
  47. 47. Pattern - Extension Point Engine defines only 3 elements in a list (About Me, News and Noteworthy) 1 2 3
  48. 48. Pattern - Extension Point Solution: In Engine, add Helper logic that looks up partials in a specific ext directory, and based on file name (e.g. row_7.html.erb) insert into the right location in the View. In App, define these partials with the right file names and locations.
  49. 49. Pattern - Extension Point App 1 adds “nav_bar_list_ext/_row_1.html.erb” 1 2 3 4
  50. 50. Pattern - Extension Point App 2 adds “nav_bar_list_ext/_row_4.html.erb” 1 2 3 4
  51. 51. Pattern - ConfigurableFeatures Problem: different apps need different features from an engine in different combinations
  52. 52. Pattern - ConfigurableFeatures Solution: In Engine, add logic that looks up configuration options In App, configure Engine by overriding configuration options
  53. 53. Pattern - ConfigurableFeatures Example: Engine defines engine_config.yml enable_address_extensions: true enable_address_headers: true App overrides some options in engine_config.yml Engine uses config options to customize behavior using conditionals
  54. 54. Rails Engine Costs Overhead in establishing a new Rails Engine gem project Continuous switching between projects and engines to get work done Upgrade of ref numbers in Gemfile
  55. 55. Rails Engine Benefits Code reuse across all application layers Better maintainability due to: Independent project codebases Cleanly defined boundaries between projects and reusable components (engines) Project tests get smaller and run faster
  56. 56. Engines vs Services Engines are better when: Reusing small MVC features, especially domain independent (e.g. Search Map) Preferring to avoiding network and infrastructure overhead over establishing a service Wanting to quickly extract and reuse a feature
  57. 57. Engines vs Services Web Services are better when: Reusing larger MVC features that depend on domain data Need to consume feature in another programming language or outside the organization boundaries Need to scale up feature performance independently of the application (e.g. separate DB)
  58. 58. Engines vs Services To keep an easier to maintain Agile code base, start simple and then move incrementally towards a more complex architecture: Extract an MVC feature as an engine first Convert engine into a service when the need arises
  59. 59. Questions & Answers ???
  60. 60. Review Basics of Rails Engines Rails Engine Patterns Typical Development Process Summary of Benefits and Trade-Offs
  61. 61. More Info Engine.html engine.html 2990539
  62. 62. Contact Code Painter Blog: Twitter: @AndyMaleh LinkedIn: Look up “Andy Maleh”