[
  {
    "path": ".gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files for more about ignoring files.\n#\n# If you find yourself ignoring temporary files generated by your text editor\n# or operating system, you probably want to add a global ignore instead:\n#   git config --global core.excludesfile '~/.gitignore_global'\n\n# Ignore bundler config.\n/.bundle\n\n# Ignore the default SQLite database.\n/db/*.sqlite3\n/db/*.sqlite3-journal\n\n# Ignore all logfiles and tempfiles.\n/log/*.log\n/tmp\n\n.DS_Store\npublic/assets\n"
  },
  {
    "path": ".rspec",
    "content": "--color\n--format progress"
  },
  {
    "path": "Gemfile",
    "content": "require File.dirname(__FILE__) + '/lib/boot_inquirer'\n\nsource 'https://rubygems.org'\n\n# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'\ngem 'rails', '4.0.1'\n\n\ngemspec path: \"apps/shared\"\nBootInquirer.each_active_app do |app|\n  gemspec path: \"apps/#{app.gem_name}\"\nend\n\n\n# Use sqlite3 as the database for Active Record\ngem 'sqlite3'\n\n# Use SCSS for stylesheets\ngem 'sass-rails', '~> 4.0.0'\ngem 'haml'\n\n# Use Uglifier as compressor for JavaScript assets\ngem 'uglifier', '>= 1.3.0'\n\n\n# See https://github.com/sstephenson/execjs#readme for more supported runtimes\n# gem 'therubyracer', platforms: :ruby\n\n# Use jquery as the JavaScript library\ngem 'jquery-rails'\n\n# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder\n# gem 'jbuilder', '~> 1.2'\n\ngroup :doc do\n  # bundle exec rake doc:rails generates the API under doc/api.\n  gem 'sdoc', require: false\nend\n\n# Use unicorn as the app server\n# gem 'unicorn'\n\n# Use Capistrano for deployment\n# gem 'capistrano', group: :development\n\ngroup :development, :test do\n  gem 'byebug'\nend\n\ngroup :test do\n  gem 'rspec'\n  gem 'rspec-rails'\n  gem 'factory_girl_rails'\n  gem 'forgery'\n  gem 'fixture_builder'\nend\n\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2014 TaskRabbit\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Rails Engines Example\n\nThis shows how to use engines for namespacing within a \"operator\" Rails application.\n_View original\n[post](http://tech.taskrabbit.com/blog/2014/02/11/rails-4-engines/)_.\n\n## Table of contents<a name=\"top\"></a>\n- [Rails Engines](#rails-engines)\n- [Versus Many Apps](#versus-many-apps)\n- [Versus Single App](#versus-single-app)\n- [Engine Usage](#engine-usage)\n- [Admin](#admin)\n- [Shared Code](#shared-code)\n- [API Server](#api-server)\n- [Strategies](#strategies)\n- [Migrations and Models](#migrations-and-models)\n- [Admin](#admin)\n- [Assets](#assets)\n- [Routes](#routes)\n- [Tests](#tests)\n- [Memory](#memory)\n- [Folders and Files](#folders-and-files)\n- [Interaction Between Engines](#interaction-between-engines)\n- [Summary](#summary)\n\n\nAt\n[TaskRabbit](https://www.taskrabbit.com),\nwe have gone through a few iterations on how we make our app(s). In the beginning, there was the monolithic Rails app in the standard way with 100+ models and their many corresponding controllers and views. Then we moved to several apps with their own logic and often using the big one via API. Our newest\n[project](https://taskrabbit.co.uk)\nis a single \"app\" made up of several Rails engines. We have found that this strikes a great balance between the (initial) straightforwardness of the single Rails app and the modularity of the more service-oriented architecture.\n\nWe've talked about this approach with a few people and they often ask very specific questions about the tactics used to make this happen, so let's go through it here and via a\n\n[sample application](https://github.com/taskrabbit/rails_engines_example).[back to top](#top)\n\n## Rails Engines <a name=\"rails-engines\"></a>\n\n[Rails Engines](http://edgeguides.rubyonrails.org/engines.html)\nis basically a whole Rails app that lives in the container of another one. Put another way, as the docs note: an app itself is basically just an engine at the root level. Over the years, we've seen engines as parts of gems such as\n[devise](https://github.com/plataformatec/devise/blob/7a9ae13baadc3643d0f5b74077d9760d19c56adb/lib/devise/rails.rb) or\n[rails_admin](https://github.com/sferik/rails_admin/blob/master/lib/rails_admin/engine.rb).\nThese example show the power of engines by providing a large set of relatively self-contained functionality \"mounted\" into an app.\n\nAt some point, there was a talk that suggested the approach of putting my our functionality into engines and that the Rails team seemed to be devoting more and more time to make them a first class citizen. Our friends at Pivotal Labs were talking about it a lot, too. Sometimes\n[good](http://pivotallabs.com/migrating-from-a-single-rails-app-to-a-suite-of-rails-engines/)\nand sometimes\n[not so good](http://pivotallabs.com/experience-report-engine-usage-that-didn-t-work/).\n\n[back to top](#top)\n\n## Versus Many Apps <a name=\"versus-many-apps\"></a>\n\nWe'd seen an app balloon and get out of control before, leading us to try and find better ways of modularization. It was fun and somewhat liberating to say \"Make a new app!\" when there was a new problem domain to tackle. We also used it as a way to handle our growing organization. We could ask Team A to work on App A and know that they could run faster by understanding the scope was limited to that. As a side-note and in retrospect, we probably let organizational factors affect architecture way more than appropriate.\n\nLots of things were great about this scenario. The teams had freedom to explore new approaches and we learned a lot. App B could upgrade Rack (or whatever) because it depended on the crazy thing that App A depended on. App C had the terrible native code-dependent gem and we only had to put that on the App C servers. Memory usage was kept lower, allowing us to run more background workers and unicorn threads.\n\nBut things got rough in coordinating across these apps. It wasn't just the data access. We made APIs and allowed any app to have read-only access to the platform app's database. This allowed things go much faster by preventing creation of many GET endpoints and possible points of failure. The main issue in coordinating releases that spanned apps is that they just went slower than if it was one codebase. There was also interminable bumping of gem versions to get shared code to all the apps. Integration testing the whole experience was also very rough.\n\nSo it's a simple one, but the main advantage that we've seen in the engine model is that it is one codebase and git repo. A single pull request has everything related to that feature. It rolls out atomically. Gems can be bumped once and our internal gems aren't bumped at all as they live unbuilt in a `gems` folder in the app itself. We still get most of the modularization that multiple apps had. For example, the User model in the payments engine has all the stuff about balances and the one in the profile engine doesn't know anything about all that and it's various helper methods.\n\nThe issue with gem upgrades and odd server configurations does continue to exist in the engine model and is mostly fine in the many app model. The gem one is tough and we just try to stay on top of upgrading to the newest things and overall reducing dependencies. The specs will also run slower in the engine app, but you'll have better integration testing. I'll go over a little bit about we've tackled server configurations and memory further down.\n\n[back to top](#top)\n\n## Versus Single App <a name=\"versus-single-app\"></a>\n\nIt's very tempting when green-fielding a project to just revert back to the good-old-days of the original app. Man, that was so nice back before the (too) fat models and tangled views and combinatorics of 4 years of iterating screwed things up. And we've learned a lot since then too, right? Especially about saying no to all those\n[combinatorics](http://firstround.com/article/The-one-cost-engineers-and-product-managers-dont-consider)\nand also using\n[decorators](http://robots.thoughtbot.com/tidy-views-and-beyond-with-decorators)\nand\n[service objects](http://adequate.io/culling-the-activerecord-lifecycle)\nand using\n[APIs](http://www.api-first.com/).\nMaybe.\n\nWhat we do know is that you can feel that way again even a year into an app. Inside any given engine, you have the scope of a much smaller project. Some engines may grow larger and you'll start to use those tools to keep things under control. Some will (correctly) have limited scope and feel like a simple app in which you understand everything that is happening. For example, decorators are great tool and they came in handy in our big app and larger engines. However, we've found in an a targeted engine that only serves its one purpose, it feels like there is room in that model to have some things that would have been decorated in a larger app. This is because it doesn't have all that other junk in it. Only this engine's junk :-)\n\n[back to top](#top)\n\n## Engine Usage <a name=\"engine-usage\"></a>\n\nWe've seen a few different ways to use engines in a Rails project. A few examples are below. The basic variables are what is in the \"operator\" (root) app and what kind of app we're making (API driven or not).\n\n[back to top](#top)\n\n### Admin <a name=\"admin\"></a>\n\nThe first engine we've recommend making to people is the admin engine. In the first app, we made the mistake of putting admin functionality in the \"normal\" pages. It was very enticing. We had that form already for the user to edit it. Just by changing the permissions, we could allow the admin to edit it, too. Forms are cheap and admins want extra fields. And more info. And basically a different UI.\n\nSo we can made an engine basically just like rails_admin did and gave it's own layout and views and JS and models and controllers, etc. Overall, we started treating our hardworking admins like we should: a customer with their own needs and dedicated experience.\n\nThe structure looked something like this...\n\n```\napp\n  assets\n  controllers\n  models\n    user.rb\n    post.rb\n  views\n    layouts\nadmin\n  app\n    assets\n    controllers\n    models\n      admin\n        user.rb\n        post.rb\n    views\n      layouts\nconfig\ndb\n  migrate\ngems\nspec\n```\n\nWhen we had this all mixed into one interface and set of models, at least a third of the code in a model like `Post` or `User` would be admin-specific actions. With this approach, we can give the admins a better, targeted experience and keep that code in admin-land.\n\nThroughout these engine discussions, the question of sharing code and/or inheriting from objects will keep coming up. Specifically, for the admin scenario, we say do whatever works for you and on a case by case basis. In the above approach, we would probably tend to have `Admin::Post < ::Post` and other such inheritance. In Rails 2, we probably wouldn't have done what as they would have different `attr_accessible` situations but that's happening in the controller these days, so now inheriting from them will just get the benefit of the data validations, which is something we definitely want to share.\n\nNote that inheriting is probably a bad choice if you have callbacks in the root model that you don't want triggered when the admin saves the record. In that case, it would be better to `Admin::Post < ActiveRecord::Base` and either duplicate the logic, have it only in SQL table (unique indexes for example), or have a mixin that is included in both.\n\n[back to top](#top)\n\n### Shared Code <a name=\"shared-code\"></a>\n\nThe note about controllers being in charge of the parameters involved leads to the next possibility. You can have your models (at least the ones you need to have shared) in the operator and all the other stuff in the engines. At this point, maybe you could add the `engines` namespace to be more clear.\n\n```\napp\n  models\n    user.rb\n    post.rb\nconfig\ndb\n  migrate\nengines\n  customer\n    app\n      assets\n      controllers\n      models\n        customer\n          something_admin_doesnt_use.rb\n      views\n        layouts\n  admin\n    app\n      assets\n      controllers\n      models\n        admin\n          admin_notes.rb\n      views\n        layouts\ngems\nspec\n```\n\nNow you can use `Post` from both and everything is just fine. This would work out well if it's mostly the data definition you are using and like to use things like decorators and/or service objects and/or fat controllers in your engines.\n\nYou could also put layouts or mixins in the operator. This might be a good idea if you were sharing the layout between two engines. At that point, maybe we'll just go all in on the engines by making a `shared` engine. Having a namespace for clarity is much simpler.\n\n```\napps\n  shared\n    app\n      assets\n      controllers\n        shared\n          authentication.rb\n      models\n        shared\n          post.rb\n          user.rb\n      views\n        shared\n          layouts\n  marketing\n    app\n      controllers\n        marketing\n          application_controller.rb\n          home_controller.rb\n  content\n    controllers\n    models\n      content\n        something_admin_doesnt_use.rb\n  admin\n    app\n      assets\n      controllers\n      models\n        admin\n          admin_notes.rb\n      views\n        layouts\nconfig\ndb\n  migrate\ngems\nspec\n```\n\nIn this structure, admin can still get it's own layout if it wants, but marketing and content can easily share the same layout in addition to the models.\n\nThe\n[example in Github](https://github.com/taskrabbit/rails_engines_example)\ntakes this just one step farther by not sharing models at all. Sharing the actual model can still lead to the\n[god model](http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/)\nsituation of a mono-Rails app without the use of other mitigating objects. To keep things as tight as possible, we've allowed each engine to have their own\n[User](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/content/app/models/content/user.rb)\nobject, for example. If there is model code to share, it would still go in the shared engine, but as a mixin like\n[this one](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/shared/app/models/shared/user/display.rb).\nNote that in a well-designed schema, only one of these actually writes to the database and the others include a `ReadOnly` module from the shared engine.\n\nThe repo's structure looks as follows:\n\n```\napps\n  shared\n    app\n      assets\n      controllers\n        shared\n          controller\n            authentication.rb\n      models\n        shared\n          model\n            read_only.rb\n          user\n            user_display.rb\n      views\n        shared\n          layouts\n  marketing\n    app\n      controllers\n        marketing\n          application_controller.rb\n          home_controller.rb\n        models\n          marketing\n            user.rb\n    db\n      migrate\n  account\n    app\n      controllers\n      models\n        content\n          user.rb\n          post.rb\n    db\n      migrate\n  content\n    app\n      assets\n      controllers\n      models\n        admin\n          post.rb\n          user.rb\n    db\n      migrate\n  admin\n    app\n      assets\n      controllers\n      models\n        admin\n          admin_notes.rb\n          post.rb\n          user.rb\n      views\n        layouts\n    db\n      migrate\nconfig\ngems\nspec\n```\n\n[back to top](#top)\n\n### API Server <a name=\"api-server\"></a>\n\nOur latest project at TaskRabbit basically looks the the above and the\n[example](https://github.com/taskrabbit/rails_engines_example)\nwith one difference: we don't share layouts between our engines. We've made the choice to have all the frontend code in one engine and all of the other engines just serve API endpoints. There are several shared mixins for these backend engines, but they don't need a layout because they are just using\n[jbuilder](https://github.com/rails/jbuilder)\nto send back JSON to the frontend client. The frontend engine, therefore, doesn't really use any models and has all the assets and such. Admin still has its own layout and uses a more traditional Rails MVC approach.\n\nIt looks like this:\n\n```\napps\n  shared\n    app\n      assets\n      controllers\n        shared\n          controller\n            authentication.rb\n      models\n        shared\n          model\n            read_only.rb\n          user\n            user_display.rb\n  frontend\n    app\n      assets\n      controllers\n        marketing\n          application_controller.rb\n          home_controller.rb\n        models\n          marketing\n            user.rb\n      views\n        frontend\n          layouts\n  account\n    app\n      controllers\n      models\n        content\n          user.rb\n          post.rb\n      views\n        account\n          users\n            show.json.jbuilder\n    db\n      migrate\n  content\n    app\n      controllers\n      models\n        admin\n          post.rb\n          user.rb\n      views\n    db\n      migrate\n  admin\n    app\n      assets\n      controllers\n      models\n        admin\n          admin_notes.rb\n          post.rb\n          user.rb\n      views\n        layouts\n    db\n      migrate\nconfig\ngems\nspec\n```\n\nThe API setup alleviates one of the odder things about the example approach. Ideally, there is no interaction between engines. Particularly in the models and views, this is critical. However, some knowledge leaks out in the example though the controllers. For example, the\n[login controller](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account/app/controllers/account/application_controller.rb#L11)\nredirects to `/posts` after login. This is in the content engine. It's probably not the end of the world but that is coupling. We get around this using our one frontend engine and the several API ones, but this does some serious commitment.\n\n[back to top](#top)\n\n## Strategies <a name=\"strategies\"></a>\n\nWe've gotten lots of questions and read about issues people are having with engines so let's go through them here.\n\n[back to top](#top)\n\n### Migrations and Models <a name=\"migrations-and-models\"></a>\n\nRails bills itself as \"convention over configuration\" so it's not too surprising to be confronted with lots of questions about \"where to put stuff\" when deviating (slightly) from the conventions. The one people seem the most worried about are migrations. We've never had an issue, but there must be scenarios that get a little tricky. If you are sharing the models, we would just put them in the normal `db/migrate` location. If your models live inside the engines, it's probably not a huge deal to still do that, but we've decided to have the migrations live with their models.\n\nAs notes, each model/table (say `users`) ideally has one master model. In the sample app, the `User` model's master is in the\n[account](https://github.com/taskrabbit/rails_engines_example/tree/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account)\nengine. This engine is in charge of signing up and logging in users. Fleshed out, it would also be responsible for reseting a lost password and editing account information. It's the only `User` model that\n[mentions](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account/app/models/account/user.rb#L7)\n`has_secure_password` and knows anything about that kind of thing. The rest of the engines may\n[need](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/content/app/models/content/user.rb#L5)\na `User` model but they have the `ReadOnly`\n[module](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/shared/app/models/shared/model/read_only.rb)\nto prevent actually writing to the table.\n\nTherefore, the account engine has the\n[migrations](https://github.com/taskrabbit/rails_engines_example/tree/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account/db/migrate)\nhaving to do with the users table. In order to register that migrations are within these engines, we\n[add](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account/lib/account/engine.rb)\na snippet like the following to each engine.\n\n```ruby\ninitializer 'account.append_migrations' do |app|\n  unless app.root.to_s == root.to_s\n    config.paths[\"db/migrate\"].expanded.each do |path|\n      app.config.paths[\"db/migrate\"].push(path)\n    end\n  end\nend\n```\n\nThis (via\n[here](http://pivotallabs.com/leave-your-migrations-in-your-rails-engines/))\nputs the engine's migrations in the path. Migrations continue to work as they normally do with the timestamps and such. So our `db/migrate` folder doesn't have any files in it (and is not checked into git). I have one locally, just because when I make a migration, Rails creates it automatically. However, I end up doing something like this immediately.\n\n```bash\n$ bundle exec rails g migration CreatePosts\n      invoke  active_record\n      create    db/migrate/20140207011608_create_posts.rb\n$ mv db/migrate/20140207011608_create_posts.rb apps/content/db/migrate\n```\n\nYou might wonder, and it does come up, what to do when you are adding a column to the users table for some other feature in some other engine. For example, we added a boolean `admin` column to the example users table to know if the given user is allowed to do stuff in the admin engine. We see the notion of permissions as being within the account engine's scope, even if it's not being actively leveraged there. It's still part of the account. Therefore, we\n[added](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account/db/migrate/20140207164357_add_admin_to_users.rb)\nthe migration to the account engine.\n\nIn part, if I couldn't justify to myself why it would be part of the account engine, it would be a red flag. Specifically, should this even be in the users table at all. If the answer is \"yes\" for whatever reason, then I'd likely still put the migration in the account engine, but usually it helps me realize that it shouldn't be in the users table at all. A good example that came up in our app was the notion of profile. It seemed like it was 1-to-1 with users and what ever columns supported it should go in the users table. For a variety of reasons, including that we wanted a different engine for that, we ended up making it's own table with a a `has_one` relationship in that engine. This paid off even further as we realized that a `User` should actually have two profiles, one for their activity as a TaskPoster and one as a TaskRabbit, as they record and display very different information. Each has their own table and engine now.\n\nLet's say we wanted to cache the number of posts the user had made. That's a pretty clearcut case to use `counter_cache` and put a `posts_count` in the users table. We'll want to look closely at this situation. First of all, the `counter_cache` code would clearly go on the `User` model in the content engine. That would also require that model to not be read-only or at least not in spirit (depending on the specifics used to implement the feature). It's not a good feeling when you do all this architecture stuff and it gets in the way of something that is so easy and we have to look out for those cases. If this is one of those cases, just do it; literally, however you want. We would probably keep the migration in the account engine.\n\nIt might not be one of those cases, though. I have almost never been sorry when I've made another model in these cases. So we could make a `PostStatistic` model or something in the content engine which `belongs_to :user` for recording this (and likely other things that come up). The counter cache feature is not magic - we just increment that table as necessary. It also doesn't feel that superfluous as it exists only inside that engine (which. in turn, doesn't have all the random stuff internal to other engines). We have some tables that started out that way. Mostly because we actively try not to do JOINs on our API calls, these tables ending up being the hub of the most relevant data of what has happening in our marketplace. Another option that we've used in similar situations is not to make the column at all. The content engine, or whoever is using this kind of data, would use the timestamp of the last `Post` or some other data to use as the cache key to look up all kinds of stuff in a store like memcache or Redis. If it's not there, it will take bit the bullet and calculate it and store it in the cache.\n\nAgain, architecture does not exist for fun or to get in the way. If something is super-simple and obvious and easy to maintain while doing the \"right\" way for the design is difficult and fragile, we just do it the easy way. That's the way to ship things for customers. However, we've found that in most case the rules of the system kick off useful discussions and behaviors that tend to work out quite well.\n\n[back to top](#top)\n\n### Admin <a name=\"admin\"></a>\n\nOne of the cases where it's important to really examine the value and return on investment in engine separation is with the admin engine. We believe it's a special case.\n\nIn our system, the admin engine has it's own migrations. For example, we have a model called `AdminNote` where an admin can jot down little notes about most objects in the system. It clearly owns that. But the reason this whole experience exists in the first place is that it also is able to write more or less whatever it wants to _all_ the objects in the system. This clearly violates our single-model-master rule. So we don't fight an uphill battle here by making a special case and saying that the admin engine can literally do whatever it wants. All the other engines live in complete isolation from each other for a variety of reasons. Admin can depend directly on any or all of them. It's at the top of the food chain because it needs to regulate the whole system.\n\nSo it's\n[fine](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/admin/app/models/admin/post.rb)\nif `Admin::Post < Content::Post` or just uses `Content::Post` directly in it's controllers. It's just not worth it to share all of the data definitions and validations with when it will almost always be with engine X and admin. Note that it's important to have the same validations because admin might be in charge, but it still needs to produce valid data as that other engine will be using it.\n\nIn our much larger app, we inherit from and/or use most of the models in the system as well as service objects from other engines. We do not use outside controllers or views. Our admin engine does use it's own layout and much simpler request cycle than our much fancier frontend app. We tried to show the admin engine using a different layout in the example app, but they're both bootstrap so it might be hard to tell. The header is red in admin :-)\n\n[back to top](#top)\n\n### Assets <a name=\"assets\"></a>\n\nEveryone seems to have struggled with this one and I can't even imagine pulling apart assets if they weren't coded in a modular way at the start. However, starting with them separate in Rails 4 has been fairly straightforward. We add the following\n[code](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account/lib/account/engine.rb)\nto our engine much like the migration code.\n\n```ruby\ninitializer 'account.asset_precompile_paths' do |app|\n  app.config.assets.precompile += [\"account/manifests/*\"]\nend\n```\nYou could list all the manifests one by one, but we've found that it's simpler to just always put them in a folder created for the purpose. This works for both css and js. You would would reference those files something like this:\n\n```ruby\n= stylesheet_link_tag 'account/manifests/application'\n= javascript_include_tag 'account/manifests/application'\n```\n\n[back to top](#top)\n\n### Routes <a name=\"routes\"></a>\n\nIn an Engine, routes go within the engine directory at the\n[same](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account/config/routes.rb)\n`config/routes.rb` path. It's important to note here that in order for these routes to be put into use in the overall app, the engine needs to be mounted. In a normal engine use case, you would mount rails_admin (say to /admin) to give a namespace in the url, but we think it's important that all of these engines get mounted at the root level. You can see our root routes.rb file\n[here](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/config/routes.rb).\n\n```ruby\nRailsEnginesExample::Application.routes.draw do\n  BootInquirer.each_active_app do |app|\n    mount app.engine => '/', as: app.gem_name\n  end\nend\n```\n\nSo as expected, the operator app has no routes of it's own and it's all handled by the engines. I'll add little more about the `BootInquirer` in a bit. It is just a helper class that knows all the engines. This means that the code is functionally something more like this:\n\n```ruby\nRailsEnginesExample::Application.routes.draw do\n  mount Admin::Engine     => '/', as: 'admin'\n  mount Account::Engine   => '/', as: 'account'\n  mount Content::Engine   => '/', as: 'content'\n  mount Marketing::Engine => '/', as: 'marketing'\nend\n```\n\nIt would really clean to have something other than root in these mountings, but it doesn't seem practical or that important. We want to be able to have full control over our url structure. For example, mounting the account engine at anything but root would prevent it from handling both the `/login` and `/signup` paths. The trade-off is that two engines could claim the same URLs and conflict with much confusion. That's something we can manage with minimal effort. We've found that most engine route files start with `scope` to put most things under one directory or a few `resources` which does basically the same thing.\n\nAnother important note is to\n[use](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/account/lib/account/engine.rb#L3)\n`isolate_namespace` in your Engine declaration. That prevents various things like helper methods from leaking into other engines. This makes sense for our case because the whole point is to stay contained. Another side effect is route helpers like 'posts_path' to work as expected without needing to prefix them like `content.posts_path` in your views. I believe it might also make the parameters more regular (for example having `params[:post]` instead of `params[:content_post]`). Oh, just put it in\n[there](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/apps/admin/lib/admin/engine.rb).\n\n[back to top](#top)\n\n### Tests <a name=\"tests\"></a>\n\nMany of the issues noted\n[here](http://pivotallabs.com/experience-report-engine-usage-that-didn-t-work/)\nrevolve around testing. One of the promises of engines is the existence of the subcomponents that you could (theoretically) use in some other app. This is not the goal here. We are using engines maximize local simplicity in our application, not create a reusable library. To that end, we don't think the normal Engine testing mechanism of creating a dummy app within the engine is helpful.\n\nOn our first engine application, we put a `spec` folder within each engine and then wrote a `rspec_all.sh` script to run each of them. It was not the right way. To do that really correctly, you'd test at that level and you'd have to test again at the integration level. This is another case of it not being worth it. Now we just put all our specs in the spec\n[directory](https://github.com/taskrabbit/rails_engines_example/tree/434e687b795ec52705a3be1dd2c635f0054336d4/spec) and run `rspec spec` to run them all.\n\nEach engine has it's own directory in there to keep it somewhat separate and to be able to easily test all of a single engine and it ends up looking like a normal app's root spec folder with models, requests, controllers, etc. Much like the admin engine, there are no rules about what you can and can't use in the tests. The goal is make sure the code is right, not to follow some architectural edict. For example, in a test that checks whether a Task can be paid for, it's fine to use the models from the payment engine to make sure everything worked together well.\n\nOne thing that is interesting is\n[fixtures](http://api.rubyonrails.org/v3.2.13/classes/ActiveRecord/Fixtures.html).\nWe like using fixtures because it's a pretty good balance between speed and fully executing most of the code in out tests. We use\n[fixture_builder](https://github.com/rdy/fixture_builder)\nto save the hassle of maintaining those yml files precisely. Anyway, the issue in the case where we have multiple engine's each with their own model class is that fixtures (and\n[factories](https://github.com/thoughtbot/factory_girl)\nfor that matter) only get one class. So if you do something like this while testing in the content engine, you'd be in trouble:\n\n```ruby\ndescribe Content::Post do\n  fixtures :users\n\n  it \"should be associated with a user\" do\n    user = users(:willy)\n    post = Content::Post.new(content: \"words\")\n    post.user = user\n    post.save.should == true\n    user.posts.count.should == 1\n  end\nend\n```\n\nThis is a problem because of classes expecting to be a certain type. You'd get this error:\n\n```bash\nFailures:\n\n  1) Content::Post should be associated with a user\n     Failure/Error: post.user = user\n     ActiveRecord::AssociationTypeMismatch:\n       Content::User(#70346317272500) expected, got Account::User(#70346295701620)\n```\n\nSo the user has to be an instance of the `Content::User` and not an `Account::User` class. We use a\n[helper](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/spec/support/fixture_class_name_helper.rb)\nto say what the classes are as well as switch between them. So this test will use the correct classes:\n\n```ruby\ndescribe Content::Post do\n  fixtures :users\n\n  it \"should be associated with a user\" do\n    user = fixture(:users, :willy, Content)\n    post = Content::Post.new(content: \"words\")\n    post.user = user\n    post.save.should == true\n    user.posts.count.should == 1\n  end\nend\n```\n\nThe same sort of thing could be done with FactoryGirl too. Often, we end up just using the ids more than we would in a normal test suite. The important thing to note is to just do whatever you feel gives you the best coverage with the most return on investment for your time.\n\n[back to top](#top)\n\n### Memory <a name=\"memory\"></a>\n\nYou may have noticed the\n[BootInquirer](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/lib/boot_inquirer.rb)\nclass mentioned earlier. This is a class that know about all the engines in the system.\n\n```ruby\n  APPS = {\n      'a' => 'account',\n      'c' => 'content',\n      'm' => 'marketing',\n      'z' => 'admin'\n    }\n```\n\nIt is called from three places.\n\n```ruby\n# Gemfile\ngemspec path: \"apps/shared\"\nBootInquirer.each_active_app do |app|\n  gemspec path: \"apps/#{app.gem_name}\"\nend\n\n# application.rb\nrequire_relative \"../lib/boot_inquirer\"\nBootInquirer.each_active_app do |app|\n  require app.gem_name\nend\n\n# routes.rb\nBootInquirer.each_active_app do |app|\n  mount app.engine => '/', as: app.gem_name\nend\n```\n\nThe main point here is to simplify even further how to add a new engine to the app. The secondary point is somewhat interesting, though. One of the potential downsides of an engine-based app, over multiple apps, is the larger memory footprint (or larger scale production rollout) of some obscure and complicated native library for just one of the engines. This would not be a problem if you could \"boot\" the app with the just _some_ of the engines enabled. The `BootInquirer` makes that possible. It inspects and environment variable to know which engines to add to the gemspec and require and route towards.\n\n```\n$ ENGINE_BOOT=am bundle exec rails c\n    => will boot the account and marketing engines - but not content, admin, etc.\n$ ENGINE_BOOT=-m bundle exec rails c\n    => will boot all engines except marketing\n```\n\nWe haven't actually seen memory be that different that in our large Rails app. In fact, it is less because of a combination of Ruby upgrades and less conspicuous gem consumption. However, memory-wise this setup allows us to use our one codebase like multiple apps. In that case, we use a load balancer to map url paths to the correct app.\n\nThis is also useful in processing background workers. You would likely get an extra Resque worker or two. It's important to have a good queue strategy (different queues per engine) and to really not have the engines depend on each other to make this work, of course.\n\nIn order for this to work, we need to be more mindful of our gem usage. The first step is changing\n[application.rb](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/config/application.rb#L7)\nto say `Bundler.setup(:default, Rails.env)` instead of `Bundler.require(:default, Rails.env)` as usual. This mean we will have to explicitly require the gems we are using instead of it happening automatically. Most of those dependencies are in the engines' gemspecs and they'd have to be required anyway. However, by changing this line, we'll have to require what is needed from the main Gemfile as well. Ideally, there wouldn't be anything in\n[there](https://github.com/taskrabbit/rails_engines_example/blob/434e687b795ec52705a3be1dd2c635f0054336d4/Gemfile) at all, but we have some Rails and test stuff that all the engines use.\n\nYou may notice that the exception we made for the admin engine rears its head here. If admin depends on the other engines, you won't be able to use admin experience unless you launch the app with all those engines. This is definitely true. The servers that the admin urls route to will have to have all of the engines running. We found it was useful to quarantine admin usage anyway as there are a few requests and inputs that could blow out the heap size fairly easily.\n\n[back to top](#top)\n\n### Folders and Files <a name=\"folders-and-files\"></a>\n\nIf you're interested in this setup, you're just going to have to get used to it. There are a lot of directories. There are lot of files named the same thing. I've found that Sublime Text is better for this than Textmate. I'm a huge fan of ⌘T to open files and Sublime allows the use of the directory names in that typeahead list. If your editor doesn't do this, then you'll spend more time than you want to look through the six different `user.rb` or `application_contoller.rb` files in the project.\n\n[back to top](#top)\n\n### Interaction Between Engines <a name=\"interaction-between-engines\"></a>\n\nSo we've gone through a lot of trouble to keep that shiny new Rails app feel. Each engine has a particular goal in life and everything is nice and simple. Particularly in the API case, it writes and reads its data and generally just takes of business. But the world isn't always perfect and sometimes the engines need to talk to each other. If it's happening too much, we probably didn't modularize along the right lines and we should consider throwing them together. We don't have all the answers, but engine naming and scoping seems to be a fine art. It's very tempting to go very narrow for cleanliness and it's also very tempting to just throw stuff in to an existing one so I'm not surprised when we find that the lines are a not drawn quite right.\n\nThere are other cases, though, that are not systemic errors in engine-picking and future-prediction. It's the kind of case I talked about with the `posts_count` above. Let's say we had a good reason to make that happen. Actually let's change it just a little bit to be more realistic. Let's say we had a profile engine where user could manage his online presence. Let's also say that other users could see and rate his posts. It's a completely reasonable thing to have an average post rating shown on his profile. Does this data about posts mean that the profile pages or API should be part of the content engine? We don't think so. This is likely just one tiny detail in an engine otherwise setup to upload photos, quote favorite movies, or whatever. We just need a little average rating on the there somewhere with a link to the posts.\n\nIn this case, we use our\n[Resque Bus](https://github.com/taskrabbit/resque-bus)\ngem extensively. This is a minor add-on to\n[Resque](https://github.com/resque/resque/blob/1-x-stable/README.markdown)\nthat changes the paradigm just enough to allow us to decouple these engines. In a normal Rails apps using Resque, we would queue up a background worker to process the rating. This worker would calculate the new average rating and store it in the profile. Resque Bus uses publishing and subscription to accomplish similar goals. If you buy into this model, you have all of your engines and in this case the content engine, publishing to the bus when interesting things happen. Creation of a post or rating would be a good example. Other engines (or completely separate apps) then subscribe to events they find interesting. There can be more than one subscriber. Even when there is nothing particularly interesting to do, we've found that always having a subscriber to record the event produces a really useful log. In the rating case, though, the profile engine would also subscribe to the event and record the new rating. By one engine simply noting that something happened and the other reacting to the occurrence, we maintain the conceptual as well as physical (these engines could be on different servers) decoupling.\n\nWhat exactly gets published and how that is used is up to the developers involved. There seems to be a few options in this specific case.\n\nA) The content engine is publishing data changes. `ResqueBus.publish('post_rated', {post_id: 42, author_id: 2, rated_by: 4, rating: 4})`\nB) The content engine adds some calculations. `ResqueBus.publish('post_rated', {post_id: 42, author_id: 2, rated_by: 4, rating: 4, new_average: 4.25, total_ratings: 20})`\n\nChoosing option B is interesting for a few reasons:\n\n* It is predicting the information other engines will want to know.\n* It decreases the coupling because now the profile engine now just records the info instead of having to calculate it.\n* It creates a record of the averages in our event store. Maybe we'll draw a graph of it sometime.\n* It adds to the time required to complete the request to create the rating.\n\nThis would mean the post engine would have something like this in an initializer:\n\n```ruby\nResqueBus.dispatch('profile') do\n  subscribe 'post_rated' do |attributes|\n    profile = Profile::Document.find_by(user_id: attributes['author_id'])\n    profile.post_ratings_total  = attributes['total_ratings']\n    profile.post_rating_average = attributes['new_average']\n    profile.save!\n  end\nend\n```\n\nOr in the way that we prefer using a subscriber class that we would put in `profile/app/subscribers`:\n\n```ruby\nclass Profile::ContentSubscriber\n  include ResqueBus::Subscriber\n\n  subscribe :post_created\n\n  def post_created(attributes)\n    profile = Profile::Document.find_by(user_id: attributes['post_author_id'])\n    profile.post_ratings_total  = attributes['total_ratings']\n    profile.post_rating_average = attributes['new_average']\n    profile.save!\n  end\nend\n```\n\nIt's clearly a fine option and the added time probably isn't too much assuming we have the right indexes on our database, but we actually tend to use option A. We don't particularly like trying to predict which events are interesting and how other engines will use them so we just publish on all creations or updates. We are fine with the profile engine having read-only `Rate` model and code to calculate the average. It could keep a running tally of the total number and just add this one to it, but we tend to recalculate it every time because it's not that hard and is less fragile.\n\nIt would look something like this:\n\n```ruby\nclass Profile::ContentSubscriber\n  include ResqueBus::Subscriber\n\n  subscribe :post_rated\n\n  def post_rated(attributes)\n    total = Profile::Rate.where(author_id: attributes['author_id']).count\n    sum   = Profile::Rate.where(author_id: attributes['author_id']).sum(:rating)\n\n    profile = Profile::Document.find_by(user_id: attributes['post_author_id'])\n    profile.post_ratings_total  = total\n    profile.post_rating_average = sum.to_f / (5*total.to_f)\n    profile.save!\n  end\nend\n```\n\nHowever you do it, the point is that this engine is working on it's own for it's own purposes. Layering it on, it's quite straightforward to see how we could build spam detection as its own engine or into the admin one. We could subscribe to ratings or post creation and react accordingly, maybe pulling the post or giving the user a score that limits his visibility, etc. Or we could add a metrics engine, to report the conversion of a user on his first post to a variety of external services. Then, when a new developer starts and asks where the metrics code is, we don't have to say what we said before which was, \"everywhere.\" We could show very simple mappings between things that are happening throughout the system and the numbers like revenue or engagement that are getting reported to something like Google Analytics.\n\n[back to top](#top)\n\n## Summary <a name=\"summary\"></a>\n\nTry out engines. We like them.\n"
  },
  {
    "path": "Rakefile",
    "content": "# Add your own tasks in files placed in lib/tasks ending in .rake,\n# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.\n\nrequire File.expand_path('../config/application', __FILE__)\n\nRailsEnginesExample::Application.load_tasks\n"
  },
  {
    "path": "apps/account/README.md",
    "content": "# Account\n\nSignup, login, user management\n"
  },
  {
    "path": "apps/account/account.gemspec",
    "content": "$:.push File.expand_path(\"../lib\", __FILE__)\n\n# Describe your gem and declare its dependencies:\nGem::Specification.new do |s|\n  s.name        = \"account\"\n  s.version     = \"0.0.1\"\n  s.authors     = [\"Brian Leonard\"]\n  s.email       = [\"brian@bleonard.com\"]\n  s.homepage    = \"https://github.com/taskrabbit/rails_engines_example\"\n  s.summary     = \"Account pages\"\n  s.description = \"Users!\"\n\n  s.files = Dir[\"{app,config,db,lib}/**/*\", \"MIT-LICENSE\", \"Rakefile\"]\n  s.test_files = Dir[\"spec/**/*\"]\n\n  s.add_dependency \"rails\",       \"~> 4.0.1\"\n  s.add_dependency \"bcrypt-ruby\", \"~> 3.1.2\"  # has_secure_password\nend\n"
  },
  {
    "path": "apps/account/app/controllers/account/application_controller.rb",
    "content": "module Account\n  class ApplicationController < ActionController::Base\n    # Prevent CSRF attacks by raising an exception.\n    # For APIs, you may want to use :null_session instead.\n    protect_from_forgery with: :exception\n    \n    include Shared::Controller::Layout\n\n    def login!(user)\n      session[:current_user_id] = user.id\n      redirect_to '/posts'\n    end\n\n    def logout!\n      session.delete(:current_user_id)\n      redirect_to '/'\n    end\n  end\n  \nend\n\n\n\n"
  },
  {
    "path": "apps/account/app/controllers/account/login_controller.rb",
    "content": "module Account\n  class LoginController < ::Account::ApplicationController\n    helper Shared::Helper::Errors\n\n    def new\n      login!(current_user) and return if current_user\n      @user = Account::User.new\n    end\n\n    def create\n      @user = Account::User.find_by_email(account_params[:email])\n      try_again and return unless @user\n      try_again and return unless @user.authenticate(account_params[:password])\n      login!(@user)\n    end\n\n    def destroy\n      logout!\n    end\n\n    protected\n\n    def try_again\n      @user = Account::User.new(account_params)\n      @user.errors.add(:base, \"Account not found.\")\n      render :new\n    end\n\n    def account_params\n      params.require(:user).permit(:email, :password)\n    end\n  end\nend\n"
  },
  {
    "path": "apps/account/app/controllers/account/users_controller.rb",
    "content": "module Account\n  class UsersController < ::Account::ApplicationController\n    helper Shared::Helper::Errors\n\n    def new\n      login!(current_user) and return if current_user\n      @user = Account::User.new\n    end\n\n    def create\n      @user = User.new(account_params)\n      if @user.save\n        login!(@user)\n      else\n        render :new\n      end\n    end\n\n    protected\n\n    def account_params\n      params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)\n    end\n  end\nend\n"
  },
  {
    "path": "apps/account/app/models/account/user.rb",
    "content": "require 'bcrypt'\n\nmodule Account\n  class User < ActiveRecord::Base\n    self.table_name = :users\n\n    has_secure_password\n\n    validates :email, presence: true, uniqueness: true\n    validates :first_name, :last_name, presence: true\n  end\nend\n"
  },
  {
    "path": "apps/account/app/views/account/login/new.haml",
    "content": "%h1 Log In\n\n= show_object_errors(@user)\n\n= form_for @user, url: login_path do |f|\n  .form-group\n    = f.label :email\n    = f.text_field :email, class: 'form-control'\n\n  .form-group\n    = f.label :password\n    = f.password_field :password, class: 'form-control'\n\n  = f.submit \"Log In\", class: \"btn btn-primary\"\n"
  },
  {
    "path": "apps/account/app/views/account/users/new.haml",
    "content": "%h1 Sign Up\n\n= show_object_errors(@user)\n\n= form_for @user, url: signup_path do |f|\n  .form-group\n    = f.label :first_name\n    = f.text_field :first_name, class: 'form-control'\n\n  .form-group\n    = f.label :last_name\n    = f.text_field :last_name, class: 'form-control'\n\n  .form-group\n    = f.label :email\n    = f.text_field :email, class: 'form-control'\n\n  .form-group\n    = f.label :password\n    = f.password_field :password, class: 'form-control'\n\n  .form-group\n    = f.label :password_confirmation\n    = f.password_field :password_confirmation, class: 'form-control'\n\n  = f.submit \"Create Account\", class: \"btn btn-primary\"\n"
  },
  {
    "path": "apps/account/config/routes.rb",
    "content": "Account::Engine.routes.draw do\n  get  'signup' => 'users#new'\n  post 'signup' => 'users#create'\n\n  get  'login'  => 'login#new'\n  post 'login'  => 'login#create'\n  get  'logout' => 'login#destroy'\nend\n"
  },
  {
    "path": "apps/account/db/migrate/20140128234906_create_users.rb",
    "content": "class CreateUsers < ActiveRecord::Migration\n  def change\n    create_table :users do |t|\n      t.string :first_name\n      t.string :last_name\n      t.string :email, null: false\n      t.string :password_digest\n    end\n  end\nend\n"
  },
  {
    "path": "apps/account/db/migrate/20140207012153_add_timestamp_to_users.rb",
    "content": "class AddTimestampToUsers < ActiveRecord::Migration\n  def change\n    add_column :users, :created_at, :datetime\n    add_column :users, :updated_at, :datetime\n  end\nend\n"
  },
  {
    "path": "apps/account/db/migrate/20140207164357_add_admin_to_users.rb",
    "content": "class AddAdminToUsers < ActiveRecord::Migration\n  def change\n    add_column :users, :admin, :boolean, default: false\n  end\nend\n"
  },
  {
    "path": "apps/account/lib/account/engine.rb",
    "content": "module Account\n  class Engine < ::Rails::Engine\n    isolate_namespace Account\n    \n    initializer 'account.append_migrations' do |app|\n      unless app.root.to_s == root.to_s\n        config.paths[\"db/migrate\"].expanded.each do |path|\n          app.config.paths[\"db/migrate\"].push(path)\n        end\n      end\n    end\n\n    initializer 'account.asset_precompile_paths' do |app|\n      app.config.assets.precompile += [\"account/manifests/*\"]\n    end\n  end\nend\n"
  },
  {
    "path": "apps/account/lib/account.rb",
    "content": "require \"account/engine\"\n\nmodule Account\nend\n"
  },
  {
    "path": "apps/admin/README.md",
    "content": "# Admin\n\nTools for admins to keep things running smoothly\n"
  },
  {
    "path": "apps/admin/admin.gemspec",
    "content": "$:.push File.expand_path(\"../lib\", __FILE__)\n\n# Describe your gem and declare its dependencies:\nGem::Specification.new do |s|\n  s.name        = \"admin\"\n  s.version     = \"0.0.1\"\n  s.authors     = [\"Brian Leonard\"]\n  s.email       = [\"brian@bleonard.com\"]\n  s.homepage    = \"https://github.com/taskrabbit/rails_engines_example\"\n  s.summary     = \"Admin user tools\"\n  s.description = \"Adminstrate!\"\n\n  s.files = Dir[\"{app,config,db,lib}/**/*\", \"MIT-LICENSE\", \"Rakefile\"]\n  s.test_files = Dir[\"spec/**/*\"]\n\n  s.add_dependency \"rails\",       \"~> 4.0.1\"\n  s.add_dependency \"redcarpet\"\n  s.add_dependency \"kaminari\"\n  s.add_dependency \"kaminari-bootstrap\"\n\n  # admin can use other engines' models\n  s.add_dependency \"content\"\n  s.add_dependency \"account\"\nend\n"
  },
  {
    "path": "apps/admin/app/assets/javascript/admin/manifests/application.js",
    "content": "// This is a manifest file that'll be compiled into application.js, which will include all the files\n// listed below.\n//\n// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,\n// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.\n//\n// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the\n// compiled file.\n//\n// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details\n// about supported directives.\n//\n//= require jquery\n//= require jquery_ujs\n//= require bootstrap.min\n"
  },
  {
    "path": "apps/admin/app/assets/stylesheets/admin/base.css.sass",
    "content": "body\n  padding-top: 70px\n  \nfooter\n  padding-left: 15px\n  padding-right: 15px\n\n.navbar\n  background-color: maroon\n\na.panel-link.current\n  color: black\n  \na.panel-link.current:hover\n  cursor: default\n\n\n#title\n  .dl-horizontal dt\n    width: 60px\n    \n  .dl-horizontal dd \n    margin-left: 80px"
  },
  {
    "path": "apps/admin/app/assets/stylesheets/admin/manifests/application.css",
    "content": "/*\n * This is a manifest file that'll be compiled into application.css, which will include all the files\n * listed below.\n *\n * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,\n * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.\n *\n * You're free to add application-wide styles to this file and they'll appear at the top of the\n * compiled file, but it's generally better to create a new file per style scope.\n *\n *= require bootstrap.min\n *= require admin/base\n */\n"
  },
  {
    "path": "apps/admin/app/controllers/admin/application_controller.rb",
    "content": "module Admin\n  class ApplicationController < ActionController::Base\n    # Prevent CSRF attacks by raising an exception.\n    # For APIs, you may want to use :null_session instead.\n    protect_from_forgery with: :exception\n\n    layout 'admin/layouts/admin'\n    include Shared::Controller::Manifests\n    \n    helper_method :current_user\n\n    before_filter :require_admin_user\n\n    def login!(user)\n      session[:admin_user_id] = user.id\n      redirect_to '/admin'\n    end\n\n    def logout!\n      session.delete(:admin_user_id)\n      redirect_to '/admin/login'\n    end\n\n    def current_user\n      return @current_user if defined?(@current_user)\n      @current_user = nil\n      return nil unless session[:admin_user_id]\n      @current_user = Admin::User.find_by_id(session[:admin_user_id])\n    end\n\n    # for layout\n    helper_method :skip_sidebar\n    def skip_sidebar\n      @skip_sidebar = true\n    end\n\n\n    protected\n\n    def require_admin_user\n      redirect_to \"/admin/login\" and return unless current_user\n      logout! unless current_user.admin?\n    end\n\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/controllers/admin/home_controller.rb",
    "content": "module Admin\n  class HomeController < ::Admin::ApplicationController\n\n    before_action :skip_sidebar\n    \n    def index\n      @post_search = Admin::PostSearch.new\n      @user_search = Admin::UserSearch.new\n    end\n\n    def post_search\n      op = Admin::PostSearch.new(current_user)\n      if op.submit(params)\n        @results = op.results\n        if @results.size == 1\n           redirect_to @results.first\n        end\n      else\n        redirect_to root_path, alert: 'No results found'\n      end\n    end\n\n    def user_search\n      op = Admin::UserSearch.new(current_user)\n      if op.submit(params)\n        @results = op.results\n        if @results.size == 1\n           redirect_to @results.first\n        end\n      else\n        redirect_to root_path, alert: 'No results found'\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/controllers/admin/login_controller.rb",
    "content": "module Admin\n  class LoginController < ::Admin::ApplicationController\n    helper Shared::Helper::Errors\n\n    skip_before_filter :require_admin_user\n\n    def new\n      login!(current_user) and return if current_user\n      @user = Admin::User.new\n    end\n\n    def create\n      @user = Admin::User.find_by_email(account_params[:email])\n      try_again and return unless @user\n      try_again and return unless @user.authenticate(account_params[:password]) \n      try_again and return unless @user.admin?\n      login!(@user)\n    end\n\n    def destroy\n      logout!\n    end\n\n    protected\n\n    def try_again\n      @user = Admin::User.new(account_params)\n      @user.errors.add(:base, \"Account not found.\")\n      render :new\n    end\n\n    def account_params\n      params.require(:user).permit(:email, :password)\n    end\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/controllers/admin/panel_controller.rb",
    "content": "module Admin\n  class PanelController < ::Admin::ApplicationController\n    class << self\n      def parent_prefixes\n        out = super\n        if @parent_panel\n          out.unshift(\"admin/#{@parent_panel.tableize}\")\n        end\n        out\n      end\n\n      def parent_panel(parent)\n        @parent_panel = parent.to_s.singularize\n        prepend_before_filter :load_parent_object\n      end\n    end\n\n    protected\n\n    def parent_panel\n      self.class.instance_variable_get(\"@parent_panel\")\n    end\n\n    def parent_panel_class\n      return nil unless parent_panel\n      \"Admin::#{parent_panel.classify}\".constantize\n    end\n\n    def load_parent_object\n      return unless parent_panel\n      parent_obj = parent_panel_class.find(params[\"#{parent_panel}_id\"])\n      @parent = parent_obj\n      instance_variable_set(\"@#{parent_panel}\", @parent)\n      @parent\n    end\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/controllers/admin/posts_controller.rb",
    "content": "module Admin\n  class PostsController < ::Admin::PanelController\n    prepend_before_filter :fetch_object\n\n    def show\n\n    end\n\n    def edit\n\n    end\n\n    def update\n      if @post.update_attributes(object_params)\n        redirect_to @post\n      else\n        flash[:alert] = @post.errors.full_messages.join(',')\n        render :edit\n      end\n    end\n\n    protected\n\n    def fetch_object\n      @post ||= Admin::Post.find(params[:id])\n    end\n\n    def object_params\n      params.require(:post).permit!\n    end\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/controllers/admin/users_controller.rb",
    "content": "module Admin\n  class UsersController < ::Admin::PanelController\n    prepend_before_filter :fetch_object\n\n    def show\n\n    end\n\n    def posts\n      @posts = Admin::Post.where(user_id: @user.id).page(params[:page])\n    end\n\n    def edit\n\n    end\n\n    def update\n      if @user.update_attributes(object_params)\n        redirect_to @user\n      else\n        flash[:alert] = @user.errors.full_messages.join(',')\n        render :edit\n      end\n    end\n\n    protected\n\n    def fetch_object\n      @user ||= Admin::User.find(params[:id])\n    end\n\n    def object_params\n      params.require(:user).permit!\n    end\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/helpers/admin/application_helper.rb",
    "content": "module Admin\n  module ApplicationHelper\n    def display_time(time, format=:day_zone)\n      return \"\" if time.nil?\n      I18n.l(time, :format => \"%Y-%m-%d %H:%M %Z\")\n    end\n\n    def display_markdown(content)\n      return \"\" if content.blank?\n      markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)\n      markdown.render(content).html_safe\n    end\n\n    def display_property(name, value, opts = {})\n      opts = opts.reverse_merge({\n        :html_escape => true,\n      })\n\n      return \"\" if (value.is_a?(Fixnum) && value == 0 && !opts[:allow_zero]) || (value.blank? && value != false && !opts[:allow_blank])\n\n      if value.is_a?(ActiveRecord::Base)\n        case value.class.table_name.to_s\n        when \"users\"\n          opts[:formatter] ||= :link_to_name\n        end\n      end\n\n      value = value.strftime(\"%Y-%m-%d %H:%M\") if value.respond_to?(:strftime)\n      if opts[:html_escape]\n        value = h(value) if value.is_a?(String)\n        name = h(name)\n      end\n\n      value = self.send(opts[:formatter], value) if opts[:formatter]\n      value = simple_format(value.html_safe) if opts[:paragraphs]\n\n      \"<dt>#{name}</dt><dd class='value-#{name.to_s.downcase.gsub(/\\W/,\"-\")}'>#{value}</dd>\".html_safe\n    end\n\n    def display_properties(obj, *keys)\n      return nil if obj.nil?\n      options = keys.extract_options!\n\n      out = []\n      keys.each do |key|\n        name = key.to_s.titleize\n        method = key\n        value = obj.send(method)\n        if value.is_a?(Hash)\n          value.each do |hk, hv|\n            out << display_property(hk, hv, options)\n          end\n        else\n          out << display_property(name, value, options)\n        end\n      end\n      out.join(\"\\n\").html_safe\n    end\n\n    def display_name(user, limit = nil)\n      return \"\" unless user\n      user.extend(::Shared::User::Display) unless user.respond_to?(:full_name)\n      name = user.full_name\n      name = truncate(name, length: limit) if limit\n      name\n    end\n\n    def link_to_name(user, limit = nil)\n      return \"\" unless user\n      link_to display_name(user, limit), user_path(user.id)\n    end\n\n    def render_rescue(name, *args)\n      name = \"index_#{name}\" if panel_collection?\n      render name.to_s, *args\n    rescue ActionView::MissingTemplate\n      \"\"\n    end\n\n    def skip_sidebar?\n      @skip_panels || @skip_sidebar\n    end\n\n    def skip_header?\n      @skip_panels\n    end\n\n    def skip_top_bottom?\n      @skip_panels\n    end\n\n    def panel_collection?\n      @panel_collection\n    end\n\n    def skip_panels\n      @skip_panels = true\n    end\n\n    def panel_collection(options = {})\n      @panel_collection = true\n      skip_sidebar unless options[:sidebar]\n    end\n\n    def alert_bootstrap(rails)\n      case rails.to_s\n      when \"notice\"\n        \"success\"\n      when \"error\", \"alert\"\n        \"danger\"\n      else\n        # other: \"warning\"\n        \"info\"\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/models/admin/post.rb",
    "content": "module Admin\n  class Post < ::Content::Post\n\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/models/admin/user.rb",
    "content": "module Admin\n  class User < ::Account::User\n\n  end\nend\n"
  },
  {
    "path": "apps/admin/app/operations/admin/post_search.rb",
    "content": "module Admin\n\n  class PostSearch < ::Shared::Operation::Base\n\n    fields  :query\n\n    validates :query, presence: true\n    attr_reader :results\n\n    protected\n\n    def page\n      @page || 1\n    end\n\n    def perform\n      return false if self.query.blank?\n      @results = send(\"search_by_#{search_type}\")\n      @results = @results.order('posts.created_at DESC')\n      @results = @results.page(self.page).per(20)\n      @results.size > 0\n    end\n\n    # http://www.area-codes.org.uk/formatting.php\n    def search_type\n      case self.query.to_s\n      when /^\\d+$/\n        :id\n      else\n        :content\n      end\n    end\n\n    def search_by_id\n      Admin::Post.where(id: self.query.to_i)\n    end\n\n    def search_by_content\n      q = self.query\n      Admin::Post.where(\"posts.content LIKE ?\", \"%#{q}%\")\n    end\n\n  end\n\n\nend\n"
  },
  {
    "path": "apps/admin/app/operations/admin/user_search.rb",
    "content": "module Admin\n\n  class UserSearch < ::Shared::Operation::Base\n\n    fields  :query\n\n    validates :query, presence: true\n    attr_reader :results\n\n    protected\n\n    def page\n      @page || 1\n    end\n\n    def perform\n      return false if self.query.blank?\n      @results = send(\"search_by_#{search_type}\")\n      @results = @results.order('users.updated_at DESC')\n      @results = @results.page(self.page).per(20)\n      @results.size > 0\n    end\n\n    # http://www.area-codes.org.uk/formatting.php\n    def search_type\n      case self.query.to_s\n      when /^.+@.+\\..+{2,3}$/\n        :email\n      when /^\\d+$/\n        :id\n      else\n        :name\n      end\n    end\n\n    def search_by_email\n      Admin::User.where(email: self.query)\n    end\n\n    def search_by_id\n      Admin::User.where(id: self.query.to_i)\n    end\n\n    def search_by_name\n      q = self.query.split(\" \")\n      Admin::User.where(\"users.first_name LIKE ? OR users.last_name LIKE ?\", \"%#{q[0]}%\", \"%#{q[-1]}%\")\n    end\n\n  end\n\n\nend\n"
  },
  {
    "path": "apps/admin/app/views/admin/home/index.haml",
    "content": ".row\n  .col-md-6\n    = form_for @post_search, url: post_search_path, method: 'get', html: {class: 'form-inline'} do |f|\n      %fieldset\n        %legend Post Search\n        .form-group\n          = f.text_field :query, placeholder: \"content, post id\", name: 'query', class: \"form-control\", style: \"width: 300px;\"\n        = f.submit 'Post Search', class: \"btn btn-default\"\n\n  .col-md-6\n    = form_for @user_search, url: user_search_path, method: 'get', html: {class: 'form-inline'} do |f|\n      %fieldset\n        %legend User Search\n        .form-group\n          = f.text_field :query, placeholder: \"email, name, user id\", name: 'query', class: \"form-control\", style: \"width: 300px;\"\n        = f.submit 'User Search', class: \"btn btn-default\"\n"
  },
  {
    "path": "apps/admin/app/views/admin/home/post_search.haml",
    "content": "%table.table\n  %thead\n    %tr\n      %th Created At\n      %th Poster\n      %th Content\n  %tbody\n    - @results.each do |post|\n      %tr\n        %td= link_to(display_time(post.created_at), post_path(post))\n        %td= link_to_name(post.user)\n        %td= truncate(post.content, length: 120)\n"
  },
  {
    "path": "apps/admin/app/views/admin/home/user_search.haml",
    "content": "%table.table\n  %thead\n    %tr\n      %th Created At\n      %th Name\n      %th Email\n  %tbody\n    - @results.each do |user|\n      %tr\n        %td= display_time(user.created_at)\n        %td= link_to_name(user)\n        %td= link_to user.email, user\n"
  },
  {
    "path": "apps/admin/app/views/admin/layouts/admin.haml",
    "content": "!!! 5\n%html\n  %head\n    %meta{charset: 'utf-8'}\n    %meta{'http-equiv' => 'X-UA-Compatible', content: 'IE=edge,chrome=1'}\n    %meta{name: 'viewport',    content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0 user-scalable=no'}\n    %meta{name: 'apple-mobile-web-app-capable',          content: 'yes'}\n    %meta{name: 'apple-mobile-web-app-status-bar-style', content: 'black'}\n\n    %title TaskRabbit Admin\n\n    = stylesheet_link_tag 'admin/manifests/application'\n    = render_manifests('css')\n\n    = yield :javascript\n\n    = csrf_meta_tags\n\n  %body\n    .navbar.navbar-fixed-top.navbar-inverse{role: \"navigation\"}\n      .container\n        .navbar-header\n          %a.navbar-brand{href: root_path} TaskRabbit Admin\n        - if current_user\n          %ul.nav.navbar-nav.navbar-right\n            %li\n              %a{href: logout_path} Logout\n\n\n    .container\n      - if !skip_header? && (header = render_rescue(:header)).present?\n        #header.page-header\n          = header\n\n      - flash.keys.each do |name|\n        %div{class: \"alert alert-#{alert_bootstrap(name)}\"}\n          = flash[name] if flash[name].present?\n        - flash.delete(name)\n\n      .row\n        - unless skip_sidebar?\n          .col-md-3\n            - if (title = render_rescue(:title)).present?\n              #title.well\n                = title\n\n            - if (actions = render_rescue(:actions)).present?\n              #actions.well\n                = actions\n\n            - if (panels = render_rescue(:panels)).present?\n              #panels.well{role: \"navigation\"}\n                = panels\n        - col_class = skip_sidebar? ? \"\" : \"col-md-9\"\n        %div{class: col_class}\n          .container\n            - if !skip_top_bottom? && (main_head = render_rescue(:top)).present?\n              #top.row\n                = main_head\n\n            #panel.row\n              = yield\n\n            - if !skip_top_bottom? &&  (main_bottom = render_rescue(:bottom)).present?\n              #bottom.row\n                = main_bottom\n\n      %footer\n\n    = javascript_include_tag 'admin/manifests/application'\n    = render_manifests('js')\n"
  },
  {
    "path": "apps/admin/app/views/admin/login/new.haml",
    "content": "%h1 Log In\n\n= show_object_errors(@user)\n\n= form_for @user, url: login_path do |f|\n  .form-group\n    = f.label :email\n    = f.text_field :email, class: 'form-control'\n\n  .form-group\n    = f.label :password\n    = f.password_field :password, class: 'form-control'\n\n  = f.submit \"Log In\", class: \"btn btn-primary\"\n"
  },
  {
    "path": "apps/admin/app/views/admin/posts/_panels.haml",
    "content": "%ul.nav\n  %li= link_to(\"Post\", post_path(@post))\n  %li= link_to(\"Edit\", edit_post_path(@post))\n  "
  },
  {
    "path": "apps/admin/app/views/admin/posts/edit.haml",
    "content": "%h2 Edit Post\n\n= form_for @post do |f|\n  .form-group\n    = f.text_area :content, class: 'form-control'\n\n  = f.submit \"Post\", class: \"btn btn-primary\""
  },
  {
    "path": "apps/admin/app/views/admin/posts/show.haml",
    "content": "%h2 Post\n\n%dl.dl-horizontal\n  = display_properties(@post, :user, :created_at)\n\n%hr\n\n= display_markdown(@post.content)"
  },
  {
    "path": "apps/admin/app/views/admin/users/_header.haml",
    "content": "%h1=display_name(@user)"
  },
  {
    "path": "apps/admin/app/views/admin/users/_panels.haml",
    "content": "%ul.nav\n  %li= link_to(\"Account\", user_path(@user))\n  %li= link_to(\"Edit\", edit_user_path(@user))\n  %li= link_to(\"Posts\", posts_user_path(@user))"
  },
  {
    "path": "apps/admin/app/views/admin/users/edit.haml",
    "content": "%h2 Edit\n\n= form_for @user do |f|\n  .form-group\n    = f.label :first_name\n    = f.text_field :first_name, class: 'form-control'\n\n  .form-group\n    = f.label :last_name\n    = f.text_field :last_name, class: 'form-control'\n\n  .form-group\n    = f.label :email\n    = f.text_field :email, class: 'form-control'\n\n  = f.submit \"Edit\", class: \"btn btn-primary\"\n"
  },
  {
    "path": "apps/admin/app/views/admin/users/posts.haml",
    "content": "%h2 My Posts\n\n%table.table\n  %thead\n    %tr\n      %th Time\n      %th Content\n  %tbody\n    - @posts.each do |post|\n      %tr\n        %td= link_to(display_time(post.created_at), post_path(post))\n        %td= display_markdown(post.content)\n\n= paginate(@posts)"
  },
  {
    "path": "apps/admin/app/views/admin/users/show.haml",
    "content": "%h2 Info\n\n%dl.dl-horizontal\n  = display_properties(@user, :id, :email, :first_name, :last_name, :admin, :created_at)\n"
  },
  {
    "path": "apps/admin/config/routes.rb",
    "content": "Admin::Engine.routes.draw do\n  scope \"admin\" do\n\n    root to: 'home#index'\n    get 'search/posts' => \"home#post_search\", as: 'post_search'\n    get 'search/users' => \"home#user_search\", as: 'user_search'\n\n    get  'login'  => 'login#new'\n    post 'login'  => 'login#create'\n    get  'logout' => 'login#destroy', as: 'logout'\n\n    resources :users, only: [:show, :edit, :update] do\n      member do\n        get :posts\n      end\n    end\n\n    resources :posts, only: [:show, :edit, :update]\n  end\nend\n"
  },
  {
    "path": "apps/admin/lib/admin/engine.rb",
    "content": "module Admin\n  class Engine < ::Rails::Engine\n    isolate_namespace Admin\n    \n    initializer 'admin.append_migrations' do |app|\n      unless app.root.to_s == root.to_s\n        config.paths[\"db/migrate\"].expanded.each do |path|\n          app.config.paths[\"db/migrate\"].push(path)\n        end\n      end\n    end\n\n    initializer 'admin.asset_precompile_paths' do |app|\n      app.config.assets.precompile += [\"admin/manifests/*\"]\n    end\n  end\nend\n"
  },
  {
    "path": "apps/admin/lib/admin.rb",
    "content": "require \"admin/engine\"\nrequire \"kaminari\"\nrequire \"kaminari-bootstrap\"\nrequire \"redcarpet\"\n\nmodule Admin\nend\n"
  },
  {
    "path": "apps/content/README.md",
    "content": "# Content\n\nPosts, comments, etc\n"
  },
  {
    "path": "apps/content/app/assets/stylesheets/content/manifests/posts.css",
    "content": "/*\n * This is a manifest file that'll be compiled into application.css, which will include all the files\n * listed below.\n *\n * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,\n * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.\n *\n * You're free to add application-wide styles to this file and they'll appear at the top of the\n * compiled file, but it's generally better to create a new file per style scope.\n *\n *= require content/posts/index\n */\n"
  },
  {
    "path": "apps/content/app/assets/stylesheets/content/posts/index.css.sass",
    "content": ".posts-index-container\n  .post-list\n    padding-top: 20px\n\n  .post\n    .timestamp\n      float: right"
  },
  {
    "path": "apps/content/app/controllers/content/application_controller.rb",
    "content": "module Content\n  class ApplicationController < ActionController::Base\n    # Prevent CSRF attacks by raising an exception.\n    # For APIs, you may want to use :null_session instead.\n    protect_from_forgery with: :exception\n    \n    include Shared::Controller::Layout\n\n  end\nend\n"
  },
  {
    "path": "apps/content/app/controllers/content/posts_controller.rb",
    "content": "module Content\n  class PostsController < ::Content::ApplicationController\n    helper Shared::Helper::Errors\n\n    manifest :posts\n\n    before_action :require_user\n    before_action :load_post, only: [:show, :edit, :update, :destroy]\n\n    def index\n      @post = Content::Post.new\n      show_index\n    end\n\n    def create\n      @post = Post.new(post_params)\n      @post.user = current_user\n\n      if @post.save\n        flash[:notice] = \"Post saved\"\n        @post = Post.new\n      end\n      show_index\n    end\n\n    protected\n\n    def show_index\n      @posts = current_user.posts.page(params[:page]).per(20)\n      render :index\n    end\n\n    def load_post\n      @post = Content::Post.find(params[:id])\n      # say not found if not mine\n      raise ActiveRecord::RecordNotFound unless @post.user_id == current_user.id\n    end\n\n    def post_params\n      params.require(:post).permit(:content)\n    end\n  end\nend\n"
  },
  {
    "path": "apps/content/app/helpers/content/post_helper.rb",
    "content": "module Content\n  module PostHelper\n    def display_content(content)\n      markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)\n      markdown.render(content).html_safe\n    end\n\n    def display_time(datetime)\n      diff = Time.now.to_i - datetime.to_i\n      if diff.abs < 5\n        \"just now\"\n      else\n        ago = time_ago_in_words(datetime)\n        if diff > 0\n          \"#{ago} ago\"\n        else\n          \"#{ago} from now\"\n        end\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "apps/content/app/models/content/post.rb",
    "content": "module Content\n  class Post < ActiveRecord::Base\n    self.table_name = :posts\n\n    belongs_to :user, class_name: \"Content::User\"\n\n    validates :user, :content, presence: true\n  end\nend\n"
  },
  {
    "path": "apps/content/app/models/content/user.rb",
    "content": "module Content\n  class User < ActiveRecord::Base\n    self.table_name = :users\n    \n    include Shared::Model::ReadOnly\n\n    has_many :posts\n  end\nend\n"
  },
  {
    "path": "apps/content/app/views/content/posts/index.haml",
    "content": ".posts-index-container\n  %h1 Posts\n\n  = form_for @post do |f|\n    .form-group\n      = f.text_area :content, class: 'form-control'\n\n    = f.submit \"Post\", class: \"btn btn-primary\"\n\n  .post-list\n    - @posts.each do |post|\n      .post.well\n        = display_content(post.content)\n        %span.timestamp= display_time(post.created_at)\n\n= paginate(@posts)\n"
  },
  {
    "path": "apps/content/config/routes.rb",
    "content": "Content::Engine.routes.draw do\n  resources :posts, only: [:index, :create]\nend\n"
  },
  {
    "path": "apps/content/content.gemspec",
    "content": "$:.push File.expand_path(\"../lib\", __FILE__)\n\n# Describe your gem and declare its dependencies:\nGem::Specification.new do |s|\n  s.name        = \"content\"\n  s.version     = \"0.0.1\"\n  s.authors     = [\"Brian Leonard\"]\n  s.email       = [\"brian@bleonard.com\"]\n  s.homepage    = \"https://github.com/taskrabbit/rails_engines_example\"\n  s.summary     = \"Posts and such\"\n  s.description = \"Blog!\"\n\n  s.files = Dir[\"{app,config,db,lib}/**/*\", \"MIT-LICENSE\", \"Rakefile\"]\n  s.test_files = Dir[\"spec/**/*\"]\n\n  s.add_dependency \"rails\",       \"~> 4.0.1\"\n  s.add_dependency \"redcarpet\"\n  s.add_dependency \"kaminari\"\n  s.add_dependency \"kaminari-bootstrap\"\nend\n"
  },
  {
    "path": "apps/content/db/migrate/20140207011608_create_posts.rb",
    "content": "class CreatePosts < ActiveRecord::Migration\n  def change\n    create_table :posts do |t|\n      t.integer :user_id\n      t.text    :content\n      t.timestamps\n    end\n  end\nend\n"
  },
  {
    "path": "apps/content/lib/content/engine.rb",
    "content": "module Content\n  class Engine < ::Rails::Engine\n    isolate_namespace Content\n    \n    initializer 'content.append_migrations' do |app|\n      unless app.root.to_s == root.to_s\n        config.paths[\"db/migrate\"].expanded.each do |path|\n          app.config.paths[\"db/migrate\"].push(path)\n        end\n      end\n    end\n\n    initializer 'content.asset_precompile_paths' do |app|\n      app.config.assets.precompile += [\"content/manifests/*\"]\n    end\n  end\nend\n"
  },
  {
    "path": "apps/content/lib/content.rb",
    "content": "require \"content/engine\"\nrequire \"redcarpet\"\nrequire \"kaminari\"\nrequire \"kaminari-bootstrap\"\n\nmodule Content\nend\n"
  },
  {
    "path": "apps/marketing/README.md",
    "content": "# Marketing\n\nMarketing pages for introducing service and such.\n"
  },
  {
    "path": "apps/marketing/app/controllers/marketing/application_controller.rb",
    "content": "module Marketing\n  class ApplicationController < ActionController::Base\n    # Prevent CSRF attacks by raising an exception.\n    # For APIs, you may want to use :null_session instead.\n    protect_from_forgery with: :exception\n    \n    include Shared::Controller::Layout\n\n  end\n  \nend\n\n\n\n"
  },
  {
    "path": "apps/marketing/app/controllers/marketing/home_controller.rb",
    "content": "module Marketing\n  class HomeController < ::Marketing::ApplicationController\n    def index\n\n    end\n  end\nend\n"
  },
  {
    "path": "apps/marketing/app/views/marketing/home/index.haml",
    "content": "%h1 Yeah!\n"
  },
  {
    "path": "apps/marketing/config/routes.rb",
    "content": "Marketing::Engine.routes.draw do\n  root to: 'home#index'\nend\n"
  },
  {
    "path": "apps/marketing/lib/marketing/engine.rb",
    "content": "module Marketing\n  class Engine < ::Rails::Engine\n    isolate_namespace Marketing\n\n    initializer 'marketing.asset_precompile_paths' do |app|\n      app.config.assets.precompile += [\"marketing/manifests/*\"]\n    end\n  end\nend\n"
  },
  {
    "path": "apps/marketing/lib/marketing.rb",
    "content": "require \"marketing/engine\"\n\nmodule Marketing\nend\n"
  },
  {
    "path": "apps/marketing/marketing.gemspec",
    "content": "$:.push File.expand_path(\"../lib\", __FILE__)\n\n# Describe your gem and declare its dependencies:\nGem::Specification.new do |s|\n  s.name        = \"marketing\"\n  s.version     = \"0.0.1\"\n  s.authors     = [\"Brian Leonard\"]\n  s.email       = [\"brian@bleonard.com\"]\n  s.homepage    = \"https://github.com/taskrabbit/rails_engines_example\"\n  s.summary     = \"Static marketing pages\"\n  s.description = \"Sell it!\"\n\n  s.files = Dir[\"{app,config,db,lib}/**/*\", \"MIT-LICENSE\", \"Rakefile\"]\n  s.test_files = Dir[\"spec/**/*\"]\n\n  s.add_dependency \"rails\", \"~> 4.0.1\"\nend\n"
  },
  {
    "path": "apps/shared/README.md",
    "content": "# Shared\n\n## Model\n\n## Controller\n\n## Layout\n"
  },
  {
    "path": "apps/shared/app/assets/javascripts/shared/manifests/application.js",
    "content": "// This is a manifest file that'll be compiled into application.js, which will include all the files\n// listed below.\n//\n// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,\n// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.\n//\n// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the\n// compiled file.\n//\n// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details\n// about supported directives.\n//\n//= require jquery\n//= require jquery_ujs\n//= require bootstrap.min\n"
  },
  {
    "path": "apps/shared/app/assets/stylesheets/shared/base.css.sass",
    "content": "body\n  padding-top: 70px\n  \nfooter\n  padding-left: 15px\n  padding-right: 15px\n"
  },
  {
    "path": "apps/shared/app/assets/stylesheets/shared/manifests/application.css",
    "content": "/*\n * This is a manifest file that'll be compiled into application.css, which will include all the files\n * listed below.\n *\n * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,\n * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.\n *\n * You're free to add application-wide styles to this file and they'll appear at the top of the\n * compiled file, but it's generally better to create a new file per style scope.\n *\n *= require bootstrap.min\n *= require shared/base\n */\n"
  },
  {
    "path": "apps/shared/app/controllers/shared/controller/authentication.rb",
    "content": "module Shared\n  module Controller\n    module Authentication\n      extend ::ActiveSupport::Concern\n\n      included do\n        helper_method :logged_in?\n        helper_method :current_user\n      end\n\n      def current_user\n        return @current_user if defined?(@current_user)\n        @current_user = nil\n        return nil unless session[:current_user_id]\n\n        namespace = self.class.name.split('::').first\n        klass     = \"#{namespace}::User\".constantize rescue nil\n        klass   ||= Shared::User::Stub\n\n        @current_user = klass.find_by_id(session[:current_user_id])\n      end\n\n      protected\n\n      def require_user\n        redirect_to \"/\" unless current_user\n      end\n    end\n  end\nend"
  },
  {
    "path": "apps/shared/app/controllers/shared/controller/layout.rb",
    "content": "module Shared\n  module Controller\n    module Layout\n      extend ::ActiveSupport::Concern\n\n      included do\n        layout 'shared/layouts/application'\n        include Shared::Controller::Authentication\n        include Shared::Controller::Manifests\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "apps/shared/app/controllers/shared/controller/manifests.rb",
    "content": "module Shared\n  module Controller\n    module Manifests\n      extend ::ActiveSupport::Concern\n\n      included do\n        helper Shared::Controller::Manifests::Helper\n        helper_method :manifests_registered\n      end\n\n      module Helper\n        def render_manifests(type)\n          out = []\n          \n          manifests_registered(type).uniq.each do |manifest|\n            case type\n            when 'js'\n              out << javascript_include_tag(manifest)\n            when 'css'\n              out << stylesheet_link_tag(manifest)\n            end\n          end\n          out.join(\"\\n\").html_safe\n        end\n      end\n\n      def manifests_registered(type)\n        self.class.manifests_registered(type)\n      end\n\n      module ClassMethods\n        def manifests_registered(type)\n          case type\n          when 'js'\n            @js_manifests_registered  ||= []\n          when 'css'\n            @css_manifests_registered ||= []\n          end\n        end\n\n        def manifests(*args)\n          @js_manifests_registered  ||= []\n          @css_manifests_registered ||= []\n\n          args.each do |manifest|\n            engine = self.name.split(\"::\").first.underscore\n            file = \"#{engine}/manifests/#{manifest}\"\n            @js_manifests_registered  << file if Rails.application.assets.find_asset(\"#{file}.js\").present?\n            @css_manifests_registered << file if Rails.application.assets.find_asset(\"#{file}.css\").present?\n          end\n        end\n        alias :manifest :manifests\n      end\n    end\n  end\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "apps/shared/app/helpers/shared/helper/errors.rb",
    "content": "module Shared\n  module Helper\n    module Errors\n      def show_object_errors(object)\n        return \"\" if object.errors.size == 0\n        render \"/shared/layouts/errors\", object: object\n      end\n    end\n  end\nend"
  },
  {
    "path": "apps/shared/app/models/shared/model/read_only.rb",
    "content": "module Shared\n  module Model\n    module ReadOnly\n      \n      def readonly?\n        true\n      end\n\n      def delete\n        raise ReadOnlyRecord\n      end\n\n    end\n  end\nend"
  },
  {
    "path": "apps/shared/app/models/shared/operation/base.rb",
    "content": "# Operation\n#  the base implementation of a form object.\n#  the form has a set of defined fields which can be used in validations.\n#  the form object responds to `submit` and invokes validations\n#  if validations pass the `perform` method is invoked\n#  it is the responsibility of the concrete class to implement `perform`\n#\n#  Example usage:\n#   class SignupForm < ::Backend::Operation\n#\n#     fields :email, :password, :password_confirmation\n#\n#     validates :email, :password, :password_confirmation, presence: true\n#     validates :email, confirmation: true\n#\n#     validate :validate_email_is_gmail\n#\n#     protected\n#\n#     # at this point, validations have already run\n#     def perform\n#       user = User.new(self.attributes)\n#\n#       unless user.save\n#        return self.inherit_errors_from(user)\n#       end\n#\n#       true\n#     end\n#\n#     def validate_email_is_gmail\n#       unless self.email.to_s =~ /@gmail\\.com/\n#         self.errors.add(:email, :gmail)\n#         return false\n#       end\n#\n#       true\n#     end\n#   end\n#\n\nmodule Shared\n  module Operation\n    class Base\n      include ::ActiveModel::Model\n      include ::ActiveModel::Validations::Callbacks\n\n      class_attribute :_fields\n      self._fields = []\n      class_attribute :_defaults\n      self._defaults = {}\n      class_attribute :_error_map\n      self._error_map = {}\n\n\n\n      class << self\n\n        # fields can be provided in the following way:\n        # field :field1, :field2\n        # field :field3, :field4, default: 'my default'\n        # field field5: 'field5 default', field6: 'field6 default'\n        def field(*fields)\n          last_hash = fields.extract_options!\n          options   = last_hash.slice(:default, :scope)\n\n          fields << last_hash.except(:default, :scope)\n\n          fields.each do |f|\n\n            if f.is_a?(Hash)\n              f.each do |k,v|\n                field(k, options.merge(default: v))\n              end\n            else\n\n              _field(f, options)\n            end\n          end\n\n        end\n        alias_method :fields, :field\n\n        def default(pairs)\n          self._defaults = self._defaults.merge(pairs)\n        end\n        alias_method :defaults, :default\n\n        def error_map(hash)\n          self._error_map = self._error_map.merge(hash)\n        end\n\n        def inherited(base)\n          super\n          base._fields ||= self._fields\n          base._defaults ||= self._defaults\n          base._error_map ||= self._error_map\n        end\n\n        # Allows the form to be \"found\" by a user id. Used by delay functionality if included.\n        def find_by_id(user_id)\n          ns    = self.name.split('::').first\n          user  = \"#{ns}::User\".constantize.find(user_id)\n          new(user)\n        end\n\n        protected\n\n        def _field(field_name, options = {})\n          field = [options[:scope], field_name].compact.join('_')\n          self._fields += [field]\n\n          attr_accessor field.to_sym\n\n          default(field => options[:default]) if options[:default]\n        end\n\n      end\n\n\n\n      attr_reader :current_user\n\n      def initialize(current_user = nil, options = {})\n        @current_user     = current_user\n        @original_params  = {}\n        @filtered_params  = {}\n\n        self.class._defaults.each do |k,v|\n          self.send(\"#{k}=\", v.respond_to?(:call) ? v.call : v)\n        end\n      end\n\n      # for the delay functionality (if included into concrete implementation)\n      def delay_id\n        self.current_user.try(:id)\n      end\n\n\n      def submit!(params = {})\n        unless submit(params)\n          # todo: create error class for this\n          raise ActiveRecord::RecordInvalid.new(self)\n        end\n        true\n      end\n\n      # the action which should be invoked upon form submission (from the controller)\n      def submit(params = {})\n\n        @original_params = params.with_indifferent_access\n        @filtered_params = filter_params(@original_params)\n\n        apply_params(@filtered_params)\n\n        return false unless self.valid?\n\n        self.perform\n\n      rescue ActiveRecord::RecordInvalid => e\n        self.inherit_errors_from(e.record)\n        false\n      end\n\n\n      protected\n\n\n      # implement this in your concrete class.\n      def perform\n        raise NotImplementedError\n      end\n\n\n      #wrap execution with an active record base transaction\n      def transaction\n        ActiveRecord::Base.transaction do\n          yield\n        end\n      end\n\n\n      # applies the errors to the form object from the child object, optionally at the namespace provided\n      def inherit_errors_from(object, namespace = nil)\n        inherit_errors(object.errors, namespace)\n      end\n\n\n      # applies the errors in error_object to self, optionally at the namespace provided\n      # returns false so failure cases can end with this invocation\n      def inherit_errors(error_object, namespace = nil)\n        error_object.each do |k,v|\n\n          keys  = [k, [namespace, k].compact.join('_')]\n          keys  = keys.map{|key| _error_map[key.to_sym] || key }\n\n          match = keys.detect{|key| self.respond_to?(key) || @original_params.try(:has_key?, key) }\n\n          if match\n            errors.add(match, v, api_id: v.api_id)\n          else\n            errors.add(:base, error_object.full_message(k, v), api_id: v.api_id)\n          end\n\n        end\n\n        false\n      end\n\n\n      # grabs the attributes that match the given namespace\n      def namespaced_attributes(namespace, options = {})\n\n        regex = namespace.is_a?(Regexp) ? namespace : (namespace.blank? ? /(.+)/ : /^#{namespace}_(.+)/)\n\n        ActiveSupport::HashWithIndifferentAccess.new.tap do |out|\n          _fields.each do |field|\n            if field =~ regex\n              v = send(field)\n              out[$1.to_sym] = v\n            end\n          end\n        end\n      end\n\n\n      # if you want to use strong parameters or something in your form object you can do so here.\n      def filter_params(params)\n        params\n      end\n\n\n      def apply_params(params, namespace = nil)\n        params.each do |key, value|\n\n          setter = [namespace, key].compact.join('_')\n\n          if respond_to?(\"#{setter}=\") && _fields.include?(setter)\n            send(\"#{setter}=\", value)\n          elsif value.is_a?(Hash)\n            apply_params(value, setter)\n          end\n        end\n      end\n\n\n      def bool(input)\n        !!(input.to_s =~ /t|1|y|ok/)\n      end\n\n    end\n  end\nend\n"
  },
  {
    "path": "apps/shared/app/models/shared/user/display.rb",
    "content": "module Shared\n  module User\n    module Display\n\n      def display_name\n        return \"#{half_email}\" if first_name.blank?\n        return \"#{first_name}\" if last_name.blank?\n        return \"#{first_name} #{last_name[0,1]}.\"\n      end\n\n      def full_name\n        return \"#{email}\" if email.present? && first_name.blank?\n        return \"#{first_name} #{last_name}\" unless first_name.blank? || last_name.blank?\n        return \"#{first_name}\" unless first.blank?\n        return \"#{last_name}\" unless last.blank?\n        return \"\"\n      end\n\n      private\n\n      def half_email\n        return \"\" if email.blank?\n        index = email.index('@')\n        return \"\" if index.nil? || index.to_i.zero?\n        return email[0, index.to_i]\n      end\n      \n    end\n  end\nend\n"
  },
  {
    "path": "apps/shared/app/models/shared/user/stub.rb",
    "content": "module Shared\n  module User\n    class Stub < ActiveRecord::Base\n      self.table_name = :users\n\n      include Shared::Model::ReadOnly\n\n    end\n  end\nend\n"
  },
  {
    "path": "apps/shared/app/views/shared/layouts/_errors.haml",
    "content": "%ul.error_explanation.bg-danger\n  - object.errors.full_messages.each do |msg|\n    %li= msg\n"
  },
  {
    "path": "apps/shared/app/views/shared/layouts/application.haml",
    "content": "!!! 5\n%html\n  %head\n    %meta{charset: 'utf-8'}\n    %meta{'http-equiv' => 'X-UA-Compatible', content: 'IE=edge,chrome=1'}\n    %meta{name: 'viewport',    content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0 user-scalable=no'}\n    %meta{name: 'apple-mobile-web-app-capable',          content: 'yes'}\n    %meta{name: 'apple-mobile-web-app-status-bar-style', content: 'black'}\n    \n    %title Rails Engines Example\n\n    = stylesheet_link_tag 'shared/manifests/application'\n    = render_manifests('css')\n    \n  %body\n    .navbar.navbar-fixed-top.navbar-inverse{role: \"navigation\"}\n      .container\n        .navbar-header\n          %button.navbar-toggle{type: 'button', \"data-toggle\"=>\"collapse\", \"data-target\"=> \".navbar-collapse\"}\n            %span.icon-bar\n            %span.icon-bar\n            %span.icon-bar\n          %a.navbar-brand{href: \"/\"} Rails Engine Example\n        .collapse.navbar-collapse\n          %ul.nav.navbar-nav.navbar-right.dropdown\n            - if current_user\n              %li\n                %a{href: \"/posts\"} Posts\n              %li\n                %a{href: \"/logout\"} Logout\n            - else\n              %li\n                %a{href: \"/signup\"} Sign Up\n              %li\n                %a{href: \"/login\"} Log In\n          \n    .container\n      = yield\n      \n      %footer\n    \n    = javascript_include_tag 'shared/manifests/application'\n    = render_manifests('js')\n        \n"
  },
  {
    "path": "apps/shared/lib/shared/engine.rb",
    "content": "module Shared\n  class Engine < ::Rails::Engine\n    isolate_namespace Shared\n    \n    initializer 'shared.asset_precompile_paths' do |app|\n      app.config.assets.precompile += [\"shared/manifests/*\"]\n    end\n\n  end\nend\n"
  },
  {
    "path": "apps/shared/lib/shared.rb",
    "content": "require \"shared/engine\"\nrequire 'haml'\nrequire 'jquery-rails'\nrequire 'sass-rails'\n\nmodule Shared\nend\n"
  },
  {
    "path": "apps/shared/shared.gemspec",
    "content": "$:.push File.expand_path(\"../lib\", __FILE__)\n\n# Describe your gem and declare its dependencies:\nGem::Specification.new do |s|\n  s.name        = \"shared\"\n  s.version     = \"0.0.1\"\n  s.authors     = [\"Brian Leonard\"]\n  s.email       = [\"brian@bleonard.com\"]\n  s.homepage    = \"https://github.com/taskrabbit/rails_engines_example\"\n  s.summary     = \"Stuff shared between engines\"\n  s.description = \"Share it!\"\n\n  s.files = Dir[\"{app,config,db,lib}/**/*\", \"MIT-LICENSE\", \"Rakefile\"]\n  s.test_files = Dir[\"spec/**/*\"]\n\n  s.add_dependency \"rails\", \"~> 4.0.1\"\nend\n"
  },
  {
    "path": "bin/bundle",
    "content": "#!/usr/bin/env ruby\nENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)\nload Gem.bin_path('bundler', 'bundle')\n"
  },
  {
    "path": "bin/rails",
    "content": "#!/usr/bin/env ruby\nAPP_PATH = File.expand_path('../../config/application',  __FILE__)\nrequire_relative '../config/boot'\nrequire 'rails/commands'\n"
  },
  {
    "path": "bin/rake",
    "content": "#!/usr/bin/env ruby\nrequire_relative '../config/boot'\nrequire 'rake'\nRake.application.run\n"
  },
  {
    "path": "config/application.rb",
    "content": "require File.expand_path('../boot', __FILE__)\n\nrequire 'rails/all'\n\n# Note: this doesn't require the gems\n# You should require when needed\nBundler.setup(:default, Rails.env)\n\n# require railties and engines here.\nrequire_relative \"../lib/boot_inquirer\"\nrequire 'shared'\n\nBootInquirer.each_active_app do |app|\n  require app.gem_name\nend\n\nmodule RailsEnginesExample\n  class Application < Rails::Application\n    # Settings in config/environments/* take precedence over those specified here.\n    # Application configuration should go into files in config/initializers\n    # -- all .rb files in that directory are automatically loaded.\n\n    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.\n    # Run \"rake -D time\" for a list of tasks for finding time zone names. Default is UTC.\n    # config.time_zone = 'Central Time (US & Canada)'\n\n    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.\n    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]\n    config.i18n.enforce_available_locales = true\n    config.i18n.default_locale = :en\n  end\nend\n"
  },
  {
    "path": "config/boot.rb",
    "content": "# Set up gems listed in the Gemfile.\nENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)\n\nrequire 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])\n"
  },
  {
    "path": "config/database.yml",
    "content": "# SQLite version 3.x\n#   gem install sqlite3\n#\n#   Ensure the SQLite 3 gem is defined in your Gemfile\n#   gem 'sqlite3'\ndevelopment:\n  adapter: sqlite3\n  database: db/development.sqlite3\n  pool: 5\n  timeout: 5000\n\n# Warning: The database defined as \"test\" will be erased and\n# re-generated from your development database when you run \"rake\".\n# Do not set this db to the same as development or production.\ntest:\n  adapter: sqlite3\n  database: db/test.sqlite3\n  pool: 5\n  timeout: 5000\n\nproduction:\n  adapter: sqlite3\n  database: db/production.sqlite3\n  pool: 5\n  timeout: 5000\n"
  },
  {
    "path": "config/environment.rb",
    "content": "# Load the Rails application.\nrequire File.expand_path('../application', __FILE__)\n\n# Initialize the Rails application.\nRailsEnginesExample::Application.initialize!\n"
  },
  {
    "path": "config/environments/development.rb",
    "content": "RailsEnginesExample::Application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # In the development environment your application's code is reloaded on\n  # every request. This slows down response time but is perfect for development\n  # since you don't have to restart the web server when you make code changes.\n  config.cache_classes = false\n\n  # Do not eager load code on boot.\n  config.eager_load = false\n\n  # Show full error reports and disable caching.\n  config.consider_all_requests_local       = true\n  config.action_controller.perform_caching = false\n\n  # Don't care if the mailer can't send.\n  config.action_mailer.raise_delivery_errors = false\n\n  # Print deprecation notices to the Rails logger.\n  config.active_support.deprecation = :log\n\n  # Raise an error on page load if there are pending migrations\n  config.active_record.migration_error = :page_load\n\n  # Debug mode disables concatenation and preprocessing of assets.\n  # This option may cause significant delays in view rendering with a large\n  # number of complex assets.\n  config.assets.debug = true\nend\n"
  },
  {
    "path": "config/environments/production.rb",
    "content": "RailsEnginesExample::Application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # Code is not reloaded between requests.\n  config.cache_classes = true\n\n  # Eager load code on boot. This eager loads most of Rails and\n  # your application in memory, allowing both thread web servers\n  # and those relying on copy on write to perform better.\n  # Rake tasks automatically ignore this option for performance.\n  config.eager_load = true\n\n  # Full error reports are disabled and caching is turned on.\n  config.consider_all_requests_local       = false\n  config.action_controller.perform_caching = true\n\n  # Enable Rack::Cache to put a simple HTTP cache in front of your application\n  # Add `rack-cache` to your Gemfile before enabling this.\n  # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.\n  # config.action_dispatch.rack_cache = true\n\n  # Disable Rails's static asset server (Apache or nginx will already do this).\n  config.serve_static_assets = false\n\n  # Compress JavaScripts and CSS.\n  config.assets.js_compressor = :uglifier\n  # config.assets.css_compressor = :sass\n\n  # Do not fallback to assets pipeline if a precompiled asset is missed.\n  config.assets.compile = false\n\n  # Generate digests for assets URLs.\n  config.assets.digest = true\n\n  # Version of your assets, change this if you want to expire all your assets.\n  config.assets.version = '1.0'\n\n  # Specifies the header that your server uses for sending files.\n  # config.action_dispatch.x_sendfile_header = \"X-Sendfile\" # for apache\n  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx\n\n  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.\n  # config.force_ssl = true\n\n  # Set to :debug to see everything in the log.\n  config.log_level = :info\n\n  # Prepend all log lines with the following tags.\n  # config.log_tags = [ :subdomain, :uuid ]\n\n  # Use a different logger for distributed setups.\n  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)\n\n  # Use a different cache store in production.\n  # config.cache_store = :mem_cache_store\n\n  # Enable serving of images, stylesheets, and JavaScripts from an asset server.\n  # config.action_controller.asset_host = \"http://assets.example.com\"\n\n  # Precompile additional assets.\n  # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.\n  # config.assets.precompile += %w( search.js )\n\n  # Ignore bad email addresses and do not raise email delivery errors.\n  # Set this to true and configure the email server for immediate delivery to raise delivery errors.\n  # config.action_mailer.raise_delivery_errors = false\n\n  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to\n  # the I18n.default_locale when a translation can not be found).\n  config.i18n.fallbacks = true\n\n  # Send deprecation notices to registered listeners.\n  config.active_support.deprecation = :notify\n\n  # Disable automatic flushing of the log to improve performance.\n  # config.autoflush_log = false\n\n  # Use default logging formatter so that PID and timestamp are not suppressed.\n  config.log_formatter = ::Logger::Formatter.new\nend\n"
  },
  {
    "path": "config/environments/test.rb",
    "content": "RailsEnginesExample::Application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # The test environment is used exclusively to run your application's\n  # test suite. You never need to work with it otherwise. Remember that\n  # your test database is \"scratch space\" for the test suite and is wiped\n  # and recreated between test runs. Don't rely on the data there!\n  config.cache_classes = true\n\n  # Do not eager load code on boot. This avoids loading your whole application\n  # just for the purpose of running a single test. If you are using a tool that\n  # preloads Rails for running tests, you may have to set it to true.\n  config.eager_load = false\n\n  # Configure static asset server for tests with Cache-Control for performance.\n  config.serve_static_assets  = true\n  config.static_cache_control = \"public, max-age=3600\"\n\n  # Show full error reports and disable caching.\n  config.consider_all_requests_local       = true\n  config.action_controller.perform_caching = false\n\n  # Raise exceptions instead of rendering exception templates.\n  config.action_dispatch.show_exceptions = false\n\n  # Disable request forgery protection in test environment.\n  config.action_controller.allow_forgery_protection = false\n\n  # Tell Action Mailer not to deliver emails to the real world.\n  # The :test delivery method accumulates sent emails in the\n  # ActionMailer::Base.deliveries array.\n  config.action_mailer.delivery_method = :test\n\n  # Print deprecation notices to the stderr.\n  config.active_support.deprecation = :stderr\nend\n"
  },
  {
    "path": "config/initializers/backtrace_silencers.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.\n# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }\n\n# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.\n# Rails.backtrace_cleaner.remove_silencers!\n"
  },
  {
    "path": "config/initializers/debugger.rb",
    "content": "begin\n  require 'byebug'\n\n  module Kernel\n    alias :debugger :byebug\n  end\n\nrescue LoadError => e\n  # byebug isn't installed - no debugging here!\nend\n"
  },
  {
    "path": "config/initializers/filter_parameter_logging.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Configure sensitive parameters which will be filtered from the log file.\nRails.application.config.filter_parameters += [:password]\n"
  },
  {
    "path": "config/initializers/inflections.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Add new inflection rules using the following format. Inflections\n# are locale specific, and you may define rules for as many different\n# locales as you wish. All of these examples are active by default:\n# ActiveSupport::Inflector.inflections(:en) do |inflect|\n#   inflect.plural /^(ox)$/i, '\\1en'\n#   inflect.singular /^(ox)en/i, '\\1'\n#   inflect.irregular 'person', 'people'\n#   inflect.uncountable %w( fish sheep )\n# end\n\n# These inflection rules are supported but not enabled by default:\n# ActiveSupport::Inflector.inflections(:en) do |inflect|\n#   inflect.acronym 'RESTful'\n# end\n"
  },
  {
    "path": "config/initializers/mime_types.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Add new mime types for use in respond_to blocks:\n# Mime::Type.register \"text/richtext\", :rtf\n# Mime::Type.register_alias \"text/html\", :iphone\n"
  },
  {
    "path": "config/initializers/secret_token.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Your secret key is used for verifying the integrity of signed cookies.\n# If you change this key, all old signed cookies will become invalid!\n\n# Make sure the secret is at least 30 characters and all random,\n# no regular words or you'll be exposed to dictionary attacks.\n# You can use `rake secret` to generate a secure secret key.\n\n# Make sure your secret_key_base is kept private\n# if you're sharing your code publicly.\nRailsEnginesExample::Application.config.secret_key_base = 'b9908facd821d0e467ad31b4515005c1a48343ff804f06abd5bcdea144202fb8e54e6b4ae420b2179624b5ef0768f4fa4db9bf1eaa8d2a5e29b1b6963875599d'\n"
  },
  {
    "path": "config/initializers/session_store.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\nRailsEnginesExample::Application.config.session_store :cookie_store, key: '_rails_engines_example_session'\n"
  },
  {
    "path": "config/initializers/wrap_parameters.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# This file contains settings for ActionController::ParamsWrapper which\n# is enabled by default.\n\n# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.\nActiveSupport.on_load(:action_controller) do\n  wrap_parameters format: [:json] if respond_to?(:wrap_parameters)\nend\n\n# To enable root element in JSON for ActiveRecord objects.\n# ActiveSupport.on_load(:active_record) do\n#  self.include_root_in_json = true\n# end\n"
  },
  {
    "path": "config/locales/en.yml",
    "content": "# Files in the config/locales directory are used for internationalization\n# and are automatically loaded by Rails. If you want to use locales other\n# than English, add the necessary files in this directory.\n#\n# To use the locales, use `I18n.t`:\n#\n#     I18n.t 'hello'\n#\n# In views, this is aliased to just `t`:\n#\n#     <%= t('hello') %>\n#\n# To use a different locale, set it with `I18n.locale`:\n#\n#     I18n.locale = :es\n#\n# This would use the information in config/locales/es.yml.\n#\n# To learn more, please read the Rails Internationalization guide\n# available at http://guides.rubyonrails.org/i18n.html.\n\nen:\n  hello: \"Hello world\"\n"
  },
  {
    "path": "config/routes.rb",
    "content": "require 'boot_inquirer'\n\nRailsEnginesExample::Application.routes.draw do\n\n  BootInquirer.each_active_app do |app|\n    mount app.engine => '/', as: app.gem_name\n  end\nend\n"
  },
  {
    "path": "config.ru",
    "content": "# This file is used by Rack-based servers to start the application.\n\nrequire ::File.expand_path('../config/environment',  __FILE__)\nrun Rails.application\n"
  },
  {
    "path": "db/schema.rb",
    "content": "# encoding: UTF-8\n# This file is auto-generated from the current state of the database. Instead\n# of editing this file, please use the migrations feature of Active Record to\n# incrementally modify your database, and then regenerate this schema definition.\n#\n# Note that this schema.rb definition is the authoritative source for your\n# database schema. If you need to create the application database on another\n# system, you should be using db:schema:load, not running all the migrations\n# from scratch. The latter is a flawed and unsustainable approach (the more migrations\n# you'll amass, the slower it'll run and the greater likelihood for issues).\n#\n# It's strongly recommended that you check this file into your version control system.\n\nActiveRecord::Schema.define(version: 20140207164357) do\n\n  create_table \"posts\", force: true do |t|\n    t.integer  \"user_id\"\n    t.text     \"content\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n  end\n\n  create_table \"users\", force: true do |t|\n    t.string   \"first_name\"\n    t.string   \"last_name\"\n    t.string   \"email\",                           null: false\n    t.string   \"password_digest\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n    t.boolean  \"admin\",           default: false\n  end\n\nend\n"
  },
  {
    "path": "db/seeds.rb",
    "content": "# This file should contain all the record creation needed to seed the database with its default values.\n# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).\n#\n# Examples:\n#\n#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])\n#   Mayor.create(name: 'Emanuel', city: cities.first)\n"
  },
  {
    "path": "lib/assets/.keep",
    "content": ""
  },
  {
    "path": "lib/boot_inquirer.rb",
    "content": "# This determines which engines to boot / mount within the operator app (v3).\n# The boot flag is a collection of characters representing the different engines in this project\n# For example:\n#   ~> ENGINE_BOOT=am bundle exec rails c\n#   => will boot the account and marketing engines - but not content, admin, etc.\n#\n# The boot flag can be negated to have the opposite effect.\n# For example:\n#   ~> ENGINE_BOOT=-m bundle exec rails c\n#   => will boot all engines except marketing\n#\n# The boot flag characters are not necessarily the first letter of each engine name, so check this file if you're using boot flags.\n#\n# When Rails.env is \"test\" all boot flags are assumed to be present, no matter what you provide.\n\nclass BootInquirer\n  APPS = {\n    'a' => 'account',\n    'c' => 'content',\n    'm' => 'marketing',\n    'z' => 'admin'\n  }\n\n  class << self\n\n    def apps\n      APPS.map{ |k,v| BootInquirer::App.new(k, v) }\n    end\n\n    def each_active_app\n      apps.each do |app|\n        yield app if app.enabled?\n      end\n    end\n\n    def any?(*keys)\n      keys.any?{|k| send(\"#{k}?\") }\n    end\n\n    def all?(*keys)\n      keys.all?{|k| send(\"#{k}?\") }\n    end\n\n    def using_boot_flags?\n      boot_flag.present?\n    end\n\n    def method_missing(method_name, *args)\n      if method_name.to_s =~ /(.+)\\?$/\n        app = apps.detect{|app| app.gem_name == $1}\n        if app\n          app.enabled?\n        else\n          super\n        end\n      else\n        super\n      end\n    end\n\n    def boot_flag\n      @boot_flag ||= ENV['ENGINE_BOOT']\n    end\n\n    def negate?\n      boot_flag.to_s =~ /^[\\-\\^]/\n    end\n\n    def boot_flag?(flag)\n      return true if boot_flag.nil?\n\n      default_value = !!boot_flag.to_s.index(flag)\n      negate? ? !default_value : default_value\n    end\n\n  end\n\n  class App\n    attr_reader :key, :gem_name\n    def initialize(key, val)\n      @key = key\n      @gem_name = val\n    end\n\n    def enabled?\n      BootInquirer.boot_flag?(@key)\n    end\n\n    def engine\n      module_name = gem_name.classify\n      module_name << 's' if gem_name[-1] == 's'\n      module_name.constantize.const_get(:Engine)\n    end\n  end\nend\n"
  },
  {
    "path": "lib/tasks/.keep",
    "content": ""
  },
  {
    "path": "log/.keep",
    "content": ""
  },
  {
    "path": "public/404.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>The page you were looking for doesn't exist (404)</title>\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n  }\n\n  div.dialog {\n    width: 25em;\n    margin: 4em auto 0 auto;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 4em 0 4em;\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  body > p {\n    width: 33em;\n    margin: 0 auto 1em;\n    padding: 1em 0;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow:0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/404.html -->\n  <div class=\"dialog\">\n    <h1>The page you were looking for doesn't exist.</h1>\n    <p>You may have mistyped the address or the page may have moved.</p>\n  </div>\n  <p>If you are the application owner check the logs for more information.</p>\n</body>\n</html>\n"
  },
  {
    "path": "public/422.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>The change you wanted was rejected (422)</title>\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n  }\n\n  div.dialog {\n    width: 25em;\n    margin: 4em auto 0 auto;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 4em 0 4em;\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  body > p {\n    width: 33em;\n    margin: 0 auto 1em;\n    padding: 1em 0;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow:0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/422.html -->\n  <div class=\"dialog\">\n    <h1>The change you wanted was rejected.</h1>\n    <p>Maybe you tried to change something you didn't have access to.</p>\n  </div>\n  <p>If you are the application owner check the logs for more information.</p>\n</body>\n</html>\n"
  },
  {
    "path": "public/500.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>We're sorry, but something went wrong (500)</title>\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n  }\n\n  div.dialog {\n    width: 25em;\n    margin: 4em auto 0 auto;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 4em 0 4em;\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  body > p {\n    width: 33em;\n    margin: 0 auto 1em;\n    padding: 1em 0;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow:0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/500.html -->\n  <div class=\"dialog\">\n    <h1>We're sorry, but something went wrong.</h1>\n  </div>\n  <p>If you are the application owner check the logs for more information.</p>\n</body>\n</html>\n"
  },
  {
    "path": "public/robots.txt",
    "content": "# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file\n#\n# To ban all spiders from the entire site uncomment the next two lines:\n# User-agent: *\n# Disallow: /\n"
  },
  {
    "path": "spec/account/factories/user_factories.rb",
    "content": "FactoryGirl.define do\n\n  factory :user, class: Account::User do\n    sequence(:email) { |n| \"user-#{n}-#{rand(9999)}@users.com\" }\n    password '12341234'\n    password_confirmation '12341234'\n    first_name { Forgery::Name.first_name }\n    last_name  { Forgery::Name.last_name }\n  end\nend\n"
  },
  {
    "path": "spec/account/models/user_spec.rb",
    "content": "require 'spec_helper'\n\ndescribe Account::User do\n  fixtures :users\n\n  let(:user) { users(:paul) }\n  it \"should authenticate\" do\n    user.authenticate(\"12341234\").should be_true\n  end\n  \nend\n"
  },
  {
    "path": "spec/content/factories/post_factories.rb",
    "content": "FactoryGirl.define do\n\n  factory :post, class: Content::Post do\n    user { Content::User.find(FactoryGirl.create(:user).id) }\n    sequence(:content) { |n| \"#{n} words here\" }\n  end\nend\n"
  },
  {
    "path": "spec/content/models/post_spec.rb",
    "content": "require 'spec_helper'\n\ndescribe Content::Post do\n  fixtures :users\n\n  it \"should validate content\" do\n    Content::Post.new.should have(1).error_on(:content)\n  end\n\n  it \"should be associated with a user\" do\n    user = fixture(:users, :willy, Content)\n    post = Content::Post.new(content: \"words\")\n    post.user = user\n    post.save.should == true\n    user.posts.count.should == 1\n  end\n\nend\n"
  },
  {
    "path": "spec/fixtures/posts.yml",
    "content": "---\npost:\n  id: 1\n  user_id: 2\n  content: Fixtures are cool.\n  created_at: '2014-02-10 16:00:58.050118'\n  updated_at: '2014-02-10 16:00:58.050118'\n"
  },
  {
    "path": "spec/fixtures/users.yml",
    "content": "---\nwilly:\n  id: 1\n  first_name: Willy\n  last_name: Watcher\n  email: willy@example.com\n  password_digest: $2a$04$nYODEwHhzx0X/h0.sTTnNOEkaHjzA/M.WMadzNNIPONNwAn81khPm\n  created_at: '2014-02-10 16:00:57.969093'\n  updated_at: '2014-02-10 16:00:57.969093'\n  admin: f\npaul:\n  id: 2\n  first_name: Paul\n  last_name: Poster\n  email: paul@example.com\n  password_digest: $2a$04$MTxF1wejSRbCAkZ8.0Kk7.8R1/SAMOE9DVAzC8uErmCc30r6NJgl2\n  created_at: '2014-02-10 16:00:58.018112'\n  updated_at: '2014-02-10 16:00:58.018112'\n  admin: f\n"
  },
  {
    "path": "spec/shared/models/user_display_spec.rb",
    "content": "require 'spec_helper'\n\nmodule UserDisplayTest\n  class User < ActiveRecord::Base\n    self.table_name = :users\n    include Shared::User::Display\n  end\nend\n\ndescribe Shared::User::Display do\n  fixtures :users\n\n  let(:user) { fixture(:users, :paul, UserDisplayTest) }\n  it \"should calculate display names\" do\n    user.class.name.should == \"UserDisplayTest::User\"\n    user.display_name.should == \"Paul P.\"\n    user.full_name.should == \"Paul Poster\"\n\n    user.first_name = nil\n    user.last_name = nil\n    user.display_name.should == \"paul\"\n  end\nend\n"
  },
  {
    "path": "spec/spec_helper.rb",
    "content": "ENV['RAILS_ENV'] = 'test'\n\nrequire_relative \"../config/environment.rb\"\n\nrequire 'rspec/rails'\n\nrequire 'rack/utils'\nrequire 'rspec/autorun'\n\nActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)\n\nRSpec.configure do |config|\n  config.infer_base_class_for_anonymous_controllers = false\n  config.order = \"random\"\n\n  config.expect_with :rspec do |c|\n    c.syntax = [:should, :expect]\n  end\n\n  config.before(:each) do\n    Rails.cache.clear rescue nil\n\n    Time.zone = 'UTC'\n  end\n\n  # define the factories\n  require_relative 'support/test_after_commit'\n  require 'factory_girl'\n  require 'forgery'\n\n  Dir[Rails.root.join(\"spec/*/factories/**/*.rb\")].each  { |f| require f }\n\n  # configure fixture options\n  config.fixture_path               = \"#{Rails.root}/spec/fixtures/\"\n  config.use_transactional_fixtures = true\n\n  # fixup any namespace weirdness\n  require_relative 'support/fixture_class_name_helper'\n  config.include ::FixtureClassNameHelper\n\n  # build the fixtures\n  require_relative 'support/fixture_builder'\nend\n"
  },
  {
    "path": "spec/support/fixture_builder.rb",
    "content": "require 'fixture_builder'\n\nFixtureBuilder.configure do |fbuilder|\n  fbuilder.files_to_check += Dir[\"spec/*/factories/**/*.rb\", \"spec/support/fixture_builder.rb\", \"apps/*/db/seeds.rb\"]\n\n  fbuilder.factory do\n    # =================================================================\n    # Seeds\n    # =================================================================\n    load(Rails.root.join('db/seeds.rb'))\n\n    # =================================================================\n    # Account\n    # =================================================================\n    willy = fbuilder.name(:willy, FactoryGirl.create(:user, first_name: 'Willy', last_name: 'Watcher',  email: 'willy@example.com')).first\n    paul  = fbuilder.name(:paul,  FactoryGirl.create(:user, first_name: 'Paul',  last_name: 'Poster',   email: 'paul@example.com')).first\n\n    # =================================================================\n    # Content\n    # =================================================================\n    post = fbuilder.name(:post, FactoryGirl.create(:post, user_id: paul.id, content: \"Fixtures are cool.\")).first\n\n  end\n\nend\n"
  },
  {
    "path": "spec/support/fixture_class_name_helper.rb",
    "content": "# maps fixutres to their class names if different than defaults\n# gets included by spec helper in the config block\nmodule FixtureClassNameHelper\n\n  extend ::ActiveSupport::Concern\n\n  included do\n    set_fixture_class({\n      users: 'Account::User'\n    })\n  end\n\n\n  def fixture(standard_method, standard_name, override_namespace = nil)\n    model = send(standard_method, standard_name)\n\n\n    # if the override namespace is not provided this uses the current test\n    # context as a best guess for it\n    if !override_namespace && described_class\n      potential_namespace = described_class.name.split('::').first\n      if potential_namespace.constantize.const_defined?(:Engine)\n        override_namespace = potential_namespace\n      end\n    end\n\n    return model unless override_namespace\n\n    parts     = model.class.name.split('::')\n    parts[0]  = override_namespace\n    klass     = parts.join('::').constantize\n\n    klass.send(:instantiate, model.attributes)\n  end\n\nend\n"
  },
  {
    "path": "spec/support/test_after_commit.rb",
    "content": "require 'active_record/connection_adapters/abstract/transaction'\n\nmodule ActiveRecord\n  module ConnectionAdapters\n    class SavepointTransaction < ::ActiveRecord::ConnectionAdapters::OpenTransaction\n\n      def perform_commit_with_transactional_fixtures\n        out = perform_commit_without_transactional_fixtures\n        commit_records if number == 1 # last one before test one that's always there, do callbacks\n        out\n      end\n      alias_method_chain :perform_commit, :transactional_fixtures\n\n    end\n  end\nend\n"
  }
]