├── Ajax └── ajax.md ├── agile.md ├── animations.md ├── anti_patterns.md ├── asset_pipeline.md ├── bourbon.md ├── confident_ruby.md ├── cool_gems.md ├── email.md ├── flash_card_code.rb ├── flow_dock.md ├── image_preview.md ├── img ├── skill-matrix.jpg └── skills.jpg ├── junior_to_senior.md ├── markdown.md ├── omni_auth.md ├── omni_auth_devise.md ├── omni_auth_devise ├── .gitignore ├── Gemfile ├── Gemfile.lock ├── README.rdoc ├── Rakefile ├── app │ ├── assets │ │ ├── images │ │ │ └── .keep │ │ ├── javascripts │ │ │ ├── application.js │ │ │ └── products.js │ │ └── stylesheets │ │ │ ├── application.css │ │ │ ├── products.scss │ │ │ └── scaffolds.scss │ ├── controllers │ │ ├── application_controller.rb │ │ ├── callbacks_controller.rb │ │ ├── concerns │ │ │ └── .keep │ │ └── products_controller.rb │ ├── helpers │ │ ├── application_helper.rb │ │ └── products_helper.rb │ ├── mailers │ │ └── .keep │ ├── models │ │ ├── .keep │ │ ├── concerns │ │ │ └── .keep │ │ ├── product.rb │ │ └── user.rb │ └── views │ │ ├── layouts │ │ └── application.html.erb │ │ └── products │ │ ├── _form.html.erb │ │ ├── edit.html.erb │ │ ├── index.html.erb │ │ ├── new.html.erb │ │ └── show.html.erb ├── bin │ ├── bundle │ ├── rails │ ├── rake │ ├── setup │ └── spring ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── assets.rb │ │ ├── backtrace_silencers.rb │ │ ├── cookies_serializer.rb │ │ ├── devise.rb │ │ ├── filter_parameter_logging.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── session_store.rb │ │ └── wrap_parameters.rb │ ├── locales │ │ ├── devise.en.yml │ │ └── en.yml │ ├── routes.rb │ └── secrets.yml ├── db │ ├── migrate │ │ ├── 20150328151012_create_products.rb │ │ ├── 20150328151138_devise_create_users.rb │ │ └── 20150328151341_add_columns_to_users.rb │ ├── schema.rb │ └── seeds.rb ├── lib │ ├── assets │ │ └── .keep │ └── tasks │ │ └── .keep ├── log │ └── .keep ├── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ ├── favicon.ico │ └── robots.txt └── vendor │ └── assets │ ├── javascripts │ └── .keep │ └── stylesheets │ └── .keep ├── password_reset.md ├── polymorphic ├── .gitignore ├── .rspec ├── Gemfile ├── Gemfile.lock ├── README.rdoc ├── Rakefile ├── app │ ├── assets │ │ ├── images │ │ │ └── .keep │ │ ├── javascripts │ │ │ ├── application.js │ │ │ └── ratings.js │ │ └── stylesheets │ │ │ ├── application.css.scss │ │ │ └── foundation_and_overrides.scss │ ├── controllers │ │ ├── application_controller.rb │ │ ├── comments_controller.rb │ │ ├── concerns │ │ │ └── .keep │ │ ├── homes_controller.rb │ │ └── posts_controller.rb │ ├── mailers │ │ └── .keep │ ├── models │ │ ├── .keep │ │ ├── comment.rb │ │ ├── concerns │ │ │ └── .keep │ │ ├── post.rb │ │ └── user.rb │ └── views │ │ ├── comments │ │ └── _comment.html.erb │ │ ├── devise │ │ ├── confirmations │ │ │ └── new.html.erb │ │ ├── mailer │ │ │ ├── confirmation_instructions.html.erb │ │ │ ├── reset_password_instructions.html.erb │ │ │ └── unlock_instructions.html.erb │ │ ├── passwords │ │ │ ├── edit.html.erb │ │ │ └── new.html.erb │ │ ├── registrations │ │ │ ├── edit.html.erb │ │ │ └── new.html.erb │ │ ├── sessions │ │ │ └── new.html.erb │ │ ├── shared │ │ │ └── _links.html.erb │ │ └── unlocks │ │ │ └── new.html.erb │ │ ├── homes │ │ └── index.html.erb │ │ ├── layouts │ │ └── application.html.erb │ │ └── posts │ │ ├── _post.html.erb │ │ ├── new.html.erb │ │ └── show.html.erb ├── bin │ ├── bundle │ ├── rails │ ├── rake │ ├── setup │ └── spring ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── assets.rb │ │ ├── backtrace_silencers.rb │ │ ├── cookies_serializer.rb │ │ ├── devise.rb │ │ ├── filter_parameter_logging.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── session_store.rb │ │ └── wrap_parameters.rb │ ├── locales │ │ ├── devise.en.yml │ │ └── en.yml │ ├── routes.rb │ └── secrets.yml ├── db │ ├── migrate │ │ ├── 20141229145037_devise_create_users.rb │ │ ├── 20141229150559_create_posts.rb │ │ ├── 20141229153212_add_comments.rb │ │ ├── 20150113010212_add_column_to_comments.rb │ │ ├── 20150124172857_create_slugged_slugs.rb │ │ └── 20150124173135_add_slugs_to_posts.rb │ ├── schema.rb │ └── seeds.rb ├── lib │ ├── assets │ │ └── .keep │ └── tasks │ │ └── .keep ├── log │ └── .keep ├── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ ├── favicon.ico │ └── robots.txt ├── spec │ ├── features │ │ ├── user_comments_on_post_spec.rb │ │ ├── user_creates_post_spec.rb │ │ ├── user_signs_in_spec.rb │ │ ├── user_signs_out_spec.rb │ │ └── user_signs_up_spec.rb │ ├── models │ │ ├── comment_spec.rb │ │ ├── post_spec.rb │ │ └── user_spec.rb │ ├── rails_helper.rb │ ├── spec_helper.rb │ └── support │ │ ├── authentication_helper.rb │ │ ├── factory_girl.rb │ │ └── valid_attribute.rb └── vendor │ └── assets │ ├── javascripts │ └── .keep │ └── stylesheets │ └── .keep ├── rails_gems.md ├── rake_import.md ├── readme.md ├── search_feature ├── .gitignore ├── .rspec ├── Gemfile ├── Gemfile.lock ├── README.rdoc ├── Rakefile ├── app │ ├── assets │ │ ├── images │ │ │ └── .keep │ │ ├── javascripts │ │ │ └── application.js │ │ └── stylesheets │ │ │ └── application.css │ ├── controllers │ │ ├── actors_controller.rb │ │ ├── application_controller.rb │ │ ├── concerns │ │ │ └── .keep │ │ ├── movies_controller.rb │ │ └── searches_controller.rb │ ├── helpers │ │ └── application_helper.rb │ ├── mailers │ │ └── .keep │ ├── models │ │ ├── .keep │ │ ├── actor.rb │ │ ├── cast_member.rb │ │ ├── concerns │ │ │ └── .keep │ │ └── movie.rb │ └── views │ │ ├── actors │ │ ├── index.html.erb │ │ └── show.html.erb │ │ ├── layouts │ │ └── application.html.erb │ │ └── movies │ │ ├── index.html.erb │ │ └── show.html.erb ├── bin │ ├── bundle │ ├── rails │ ├── rake │ ├── setup │ └── spring ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── assets.rb │ │ ├── backtrace_silencers.rb │ │ ├── cookies_serializer.rb │ │ ├── filter_parameter_logging.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── session_store.rb │ │ └── wrap_parameters.rb │ ├── locales │ │ └── en.yml │ ├── routes.rb │ └── secrets.yml ├── db │ ├── migrate │ │ ├── 20150108143842_create_movies.rb │ │ ├── 20150108143845_create_actors.rb │ │ └── 20150108143849_create_cast_members.rb │ ├── schema.rb │ └── seeds.rb ├── lib │ ├── assets │ │ └── .keep │ └── tasks │ │ └── .keep ├── log │ └── .keep ├── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ ├── favicon.ico │ └── robots.txt ├── spec │ ├── factories.rb │ ├── features │ │ └── search_movies_spec.rb │ ├── models │ │ └── movie_spec.rb │ ├── rails_helper.rb │ └── spec_helper.rb └── vendor │ └── assets │ ├── javascripts │ └── .keep │ └── stylesheets │ └── .keep ├── tdd-rails.md ├── test_perscriptions.md ├── testing.md ├── todo.md └── warden.md /Ajax/ajax.md: -------------------------------------------------------------------------------- 1 | __orginally posted on https://coderwall.com/p/kqb3xq/rails-4-how-to-partials-ajax-dead-easy__ 2 | 3 | Consider the basic following scenario... 4 | 5 | A view with two columns: 6 | one with links of Category model instances 7 | the other empty but eager to show all the Item instances belonging to each Category. 8 | And you want to show all of that without reloading the page. I had never played much 9 | with partials in Rails, but they are really really convenient. 10 | 11 | So I have my index method 12 | items_controller.rb 13 | ```ruby 14 | def index 15 | @items = Item.all 16 | @categories = Category.all 17 | end 18 | ``` 19 | 20 | For the sake of brevity, I will simplify the views. This way you can also understand the idea and apply it to your own views. 21 | 22 | The index view contains two render calls 23 | ```erb 24 | 25 |
26 | <%= render 'sidebar_menu' %> 27 | 28 | <%= render partial: 'item_grid', locals: { items: @items} %> 29 |
30 | ``` 31 | 32 | The category links in the sidebar_menu partial are something like the following: 33 | ```erb 34 | <%= link_to cat.name, fetch_items_path(:cat_id => cat.id), :remote => true %> 35 | ``` 36 | fetch_items_path is the route that leads to our custom javascript method, which will be described next. 37 | 38 | config/routes.rb 39 | ```ruby 40 | get "/fetch_items" => 'items#from_category', as: 'fetch_items' 41 | ``` 42 | 43 | For more info on how to build custom routes, check Rails amazing documentation. 44 | 45 | **The :remote => true is the most important part here, it allows the whole Ajax business in the first place.** 46 | 47 | The item_grid partial looks like: 48 | ```erb 49 |
50 |
51 | <%= render partial: 'items_list', locals: {items: items} %> 52 |
53 |
54 | ``` 55 | The subpartial items_list just renders a list of div boxes to show our Item instances. 56 | ```erb 57 | <% items.each do |item| %> 58 |
59 | ... 60 |
61 | <% end %> 62 | ``` 63 | Now we need the method that will do the AJAX magic. For simplicity you could have something like this: 64 | 65 | items_controller.rb 66 | ```ruby 67 | def from_category 68 | @selected = Item.where(:category_id => params[:cat_id]) 69 | respond_to do |format| 70 | format.js 71 | end 72 | end 73 | ``` 74 | Notice the type of format, there's no html view because we don't need it. 75 | We're going through JS. Therefore, we need to create a javascript file, 76 | which will repopulate the div in the second column. 77 | 78 | //views/items/from_category.js.erb 79 | ```js 80 | $("#items_grid").html("<%= escape_javascript(render partial: 'items_list', locals: { items: @selected } ) %>"); 81 | ``` 82 | Let's look at this line with care. I'm rendering the same partial I was rendering in items#index, 83 | and the local variable for the partial is now the array of Item instances that match a given category. 84 | The difference is that I'm doing this through AJAX, so there's no need to reload the entire page. 85 | -------------------------------------------------------------------------------- /agile.md: -------------------------------------------------------------------------------- 1 | ### Notes from Practices of an Agile Developer 2 | * Tackle small problems while they are still small 3 | * Explore the unknown before you invest too much in it 4 | * In an Agile team the primary focus should be Outcomes. Leave ego's at the 5 | door 6 | * Outcome is what's important, not the credit, blame, or anything else 7 | * If you arn't making any mistakes youre probably not trying hard enough 8 | * There may not be a best answer, just a more suitable solution 9 | * Don't start rejecting and rewriting simply because you can't understand it 10 | right away. That's not courage; that's impatience. 11 | * A well educated team is a better team. Figure out how to level up and 12 | elevate the people around you. 13 | * It's important to have iteration schedules so you get in a state of flow with 14 | pushing features. 15 | * When doing upfront design work: discuss possible class designs in terms of 16 | responsibilities. What are classes supposed to do? What other objects will 17 | work with it to get the job done? 18 | * A good design is accurate, but not precise. 19 | 20 | -------------------------------------------------------------------------------- /animations.md: -------------------------------------------------------------------------------- 1 | # Adding Animations to Rails 2 | 3 | 1. Download animate.css 4 | 2. Put in vendor/assets/stylsheets 5 | 3. In application.scss add this line: `*= require animate` 6 | 4. Set up some JS to add animation classes when I want them. 7 | 8 | Alternatively, you can use [this gem which does those things for 9 | you](https://github.com/camelmasa/animate-rails) 10 | 11 | 12 | When adding transitions/transforms to my css here are some neat tricks: 13 | ```css 14 | .profile-icon { 15 | transition: all .2s ease-in-out; 16 | &:hover { 17 | transform: scale(1.3); 18 | } 19 | } 20 | 21 | .fa-heart.profile-icon:hover { 22 | color: #8A0707; 23 | } 24 | 25 | .fa-bar-chart.profile-icon:hover { 26 | color: #0B486B; 27 | } 28 | 29 | .fa-comments-o.profile-icon:hover { 30 | color: #3B8686; 31 | } 32 | ``` 33 | -------------------------------------------------------------------------------- /anti_patterns.md: -------------------------------------------------------------------------------- 1 | ### Rails Antipatterns 2 | 3 | When you create scopes (which are really class methods) in a model the return 4 | value will be a AR proxy object that responds to the normal interface for AR. 5 | One thing you can do to refactor fat models is make a bunch of scopes and then 6 | class methods using those scopes in order to increase readability and only have 7 | 1 long SQL statement to the DB. 8 | 9 | ### Rendering Partials - What Rails does behind the scenes 10 | 11 | ```ruby 12 | 13 | <% @posts.each do |post| 14 |

<%= post.title %>

15 |

<%= post.body %>

16 | <% end %> 17 | ``` 18 | 19 | Can then become: 20 | 21 | ```ruby 22 | 23 | <% @posts.each do |post| 24 | <%= render partial: 'post', object: :post %> 25 | <% end %> 26 | 27 | 28 |

<%= post.title %>

29 |

<%= post.body %>

30 | 31 | ``` 32 | 33 | Can then become: 34 | ```ruby 35 | 36 | <%= render partial: 'post', collection: @posts %> 37 | 38 | 39 |

<%= post.title %>

40 |

<%= post.body %>

41 | ``` 42 | 43 | Can then become: 44 | ```ruby 45 | 46 | <%= render @posts %> 47 | 48 | 49 |

<%= post.title %>

50 |

<%= post.body %>

51 | 52 | ``` 53 | 54 | ## Rails Composition 55 | 56 | When models start getting bigger its important to follow SRP and maintain that 57 | each class truly only has one purpose. 58 | 59 | For example imagine we have an Order class that has a bunch of little helper 60 | converter methods like this: 61 | 62 | ```ruby 63 | class Order < ActiveRecord::Base 64 | 65 | def to_xml 66 | ... 67 | end 68 | 69 | def to_json 70 | ... 71 | end 72 | 73 | def to_csv 74 | ... 75 | end 76 | 77 | def to_pdf 78 | ... 79 | end 80 | end 81 | ``` 82 | 83 | We could refactor this so Order's have an OrderConverter that maintains the 84 | responsibility of all those smaller helper methods. 85 | 86 | ```ruby 87 | class Order < ActiveRecord::Base 88 | def converter 89 | OrderConverter.new(self) 90 | end 91 | end 92 | 93 | class OrderConverter 94 | attr_reader :order 95 | def initialize(order) 96 | @order = order 97 | end 98 | 99 | def to_xml 100 | ... 101 | end 102 | 103 | def to_json 104 | ... 105 | end 106 | 107 | def to_csv 108 | ... 109 | end 110 | 111 | def to_pdf 112 | ... 113 | end 114 | end 115 | ``` 116 | 117 | Now we could call something like `@order.converter.to_pdf` however this is now 118 | breaking the Law of Demeter. 119 | 120 | 121 | Thats nice, but we can take it one step further and allow the Order instances to 122 | delegate those helper method calls directly to their new _composed_ object. 123 | 124 | To fix the Law of Demeter we can use Rails delegation. 125 | 126 | ```ruby 127 | class Order < ActiveRecord::Base 128 | delegate :to_xml, :to_json, :to_csv, :to_pdf, to: :converter 129 | def converter 130 | OrderConverter.new(self) 131 | end 132 | end 133 | ``` 134 | -------------------------------------------------------------------------------- /asset_pipeline.md: -------------------------------------------------------------------------------- 1 | ## Debugging Asset Pipeline 2 | 3 | * Check to see whether or not there are assets precompiled already, if so you 4 | probably need to delete those so it will re-compile them. 5 | * When using sprockets check for require_tree, it will make it so all the css 6 | files get included in a random order which might create issues. 7 | * Deploying to Heroku, check to see when you deploy the asset precompilation 8 | process occurs, if not, check your public/assets folder. 9 | 10 | 11 | ### Rails Asset Pipeline Clinic 12 | 13 | **Assets:** JavaScript, CSS, and other static files we need to properly render 14 | our pages. 15 | 16 | Solves: 17 | * Allows you to nest JS and CSS files in subdirectories 18 | * No longer need to specify the exact order to include files for third party 19 | libraries like Bootstrap or Foundation 20 | * Compresses all our assets so they get served to the browser faster 21 | * Consolidate CSS and JS files into one file so there are less HTTP requests 22 | made by the browser, improving page load speed. 23 | * Allow us to use preprocessors like Sass or Coffee Script. 24 | * Enables caching to further increase page speeds and will re cache assets when 25 | changes are made. 26 | 27 | 28 | #### Three Places To Store Assets: 29 | 30 | app/assets - file specific to current project 31 | lib/assets - files for internal libraries 32 | vendor/assets - files for external libraries 33 | 34 | #### Manifest Files 35 | 36 | app/assets/javascripts/application.js 37 | app/assets/stylesheets/application.css 38 | 39 | The manifest files specify where to find other files to load in and in which 40 | order to load them. 41 | 42 | In order to add to manifest you need there to be a comment in the beginning of 43 | the line and an equals sign. 44 | 45 | ```javascript 46 | //= require foo # single line comment 47 | 48 | /* 49 | * 50 | * 51 | *= require foo # multi line comment 52 | */ 53 | ``` 54 | 55 | #### Directive In Manifest File 56 | 57 | = require_self: Inserts content of the file itself (after directives). 58 | = require_directory: Loads all files of the same format in the specified 59 | directory in an alphabetical order. 60 | = require_tree: Just like require_directory but it also recursively requires all 61 | files in subdirectories. 62 | 63 | **Note**: Directives are loaded in the order they appear unless you use 64 | require_tree in which case there is no guarantee of the order in which the files 65 | will be included 66 | 67 | #### Search Pathes 68 | 69 | Can be edited with ``config.assets.paths << Rails.root.join('app', 'flash', 70 | 'assets')`` 71 | 72 | All standard places are added in search paths. To add fonts you could: 73 | ``app/assets/fonts`` folder since it's under the ``app/assets`` it will be 74 | included. Or you can target files in subdirectories by using a relative path: 75 | 76 | ```ruby 77 | // This will load the app/assets/javascripts/library/foo.js 78 | //= require 'library/foo' 79 | ``` 80 | 81 | **Note**: You could put CSS files in JS and JS in CSS folder and everything 82 | would work fine, people would just be annoyed at you. 83 | 84 | #### File Extensions 85 | 86 | Get compiled in the order they are given: 87 | ``products.css.sass.erb`` will run the file through the ERb engine, then sass, 88 | then deliver a css file. 89 | 90 | #### Helpers 91 | 92 | `` <%= stylesheet_link_tag "application" %>`` 93 | `` <%= javascript_include_tag "application" %>`` 94 | 95 | You can pass in different manifest files other than application to these helpers 96 | 97 | ``image_tag`` knows to search in /app/assets/images 98 | 99 | Sass Helper: 100 | ```ruby 101 | header { 102 | background-image: image-url('header-photo.png') 103 | } 104 | ``` 105 | 106 | -------------------------------------------------------------------------------- /bourbon.md: -------------------------------------------------------------------------------- 1 | ## Getting Bourbon Set Up in Rails 2 | 3 | Add gems to gemfile: 4 | ```ruby 5 | # gemfile 6 | 7 | gem 'bourbon' 8 | gem 'neat' 9 | gem 'refills' 10 | ``` 11 | 12 | Change application.css to application.scss: 13 | 14 | ```ruby 15 | /* 16 | * This is a manifest file that'll be compiled into application.css, which will include all the files 17 | * listed below. 18 | * 19 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 20 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. 21 | * 22 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 23 | * compiled file so the styles you add here take precedence over styles defined in any styles 24 | * defined in the other CSS/SCSS files in this directory. It is generally better to create a new 25 | * file per style scope. 26 | * 27 | *= require foundation_and_overrides 28 | */ 29 | 30 | @import 'bourbon'; 31 | @import 'neat'; 32 | ``` 33 | 34 | Remove all the sprockets and import the new sass libraries. 35 | 36 | This example is also using foundation along with Bourbon because it was required 37 | for the app that was being built. In general you can remove the foundation 38 | overrides as well since they shouldn't be needed if you use Neat for the grid. 39 | 40 | 41 | -------------------------------------------------------------------------------- /confident_ruby.md: -------------------------------------------------------------------------------- 1 | There are implicit and explicit type conversions. When crafting methods if you 2 | need to type check and be confident you are getting the type you are expecting 3 | to use then implement: ``to_str``, ``to_int``, or ``to_a``. 4 | 5 | Using the built in conversion functions: Array(), Integer(), etc. will do 6 | everything possible to convert an object into what you want, it will also supply 7 | stricter qualifications than the tradition .to_s methods. See page 63 for 8 | examples on how to use them. 9 | 10 | 11 | -------------------------------------------------------------------------------- /cool_gems.md: -------------------------------------------------------------------------------- 1 | ## Cool Gems w/ Descriptions: 2 | 3 | #### Devise: 4 | * user authentication. 5 | 6 | #### Ledermann-rails-settings 7 | Ruby gem to handle settings for ActiveRecord instances by storing them as serialized Hash in a separate database table. Namespaces and defaults included. 8 | -------------------------------------------------------------------------------- /email.md: -------------------------------------------------------------------------------- 1 | ## Using Email with Rails 2 | 3 | In order to get Mandrill configured properly.. follow this format: 4 | 5 | ```ruby 6 | # production.rb, test.rb, development.rb or application.rb 7 | 8 | YourApp::Application.configure do 9 | config.action_mailer.smtp_settings = { 10 | :address => "smtp.mandrillapp.com", 11 | :port => 25, # ports 587 and 2525 are also supported with STARTTLS 12 | :enable_starttls_auto => true, # detects and uses STARTTLS 13 | :user_name => "MANDRILL_USERNAME", 14 | :password => "MANDRILL_PASSWORD", # SMTP password is any valid API key 15 | :authentication => 'login', # Mandrill supports 'plain' or 'login' 16 | :domain => 'yourdomain.com', # your domain to identify your server when connecting 17 | } 18 | 19 | # … 20 | end 21 | ``` 22 | 23 | **Note** By default Heroku set up the configuration variables for Mandrill. 24 | When I was trying to get it to work I didn't realize that my environment 25 | variables were named differently from Mandrills. MAKE SURE TO DOUBLE CHECK YOUR 26 | CALLS TO ENV IN RAILS APP MATCH THE ENVIRONMENT VARIABLE NAMES ON HEROKU!!! 27 | -------------------------------------------------------------------------------- /flash_card_code.rb: -------------------------------------------------------------------------------- 1 | # Imagine were in users/index.html.haml 2 | 3 | - @post.users.where("age > 23").each do |person| 4 | = person.name 5 | 6 | 7 | # How to put Sinatra app into a Rails app 8 | 9 | class HelloApp < Sinatra::Base 10 | get '/' do 11 | "Hello World!" 12 | end 13 | end 14 | 15 | Rails.application.routes.draw do 16 | mount HelloApp, at: '/hello' 17 | end 18 | 19 | auction = Auction.find(params[:auction_id]) 20 | bid = auction.bids.find(params[:id]) 21 | 22 | # Making a good looking update 23 | class ProjectController < ApplicationController 24 | def update 25 | project = Project.find(params[:id]) 26 | if project.update(params[:project]) 27 | redirect_to project 28 | else 29 | render 'edit' 30 | end 31 | end 32 | end 33 | 34 | -------------------------------------------------------------------------------- /flow_dock.md: -------------------------------------------------------------------------------- 1 | ## Integrating Flowdock Into Rails 2 | 3 | Add flowdock gem and dotenv-rails to Gemfile: 4 | ``` 5 | gem "flowdock" 6 | 7 | group :development, :test do 8 | gem "dotenv-rails" 9 | end 10 | ``` 11 | 12 | Then add the specific flow token in .env file: 13 | 14 | ```ruby 15 | # .env file 16 | FLOWDOCK_TEST_TOKEN= 17 | ``` 18 | 19 | This implementation is for sending flows to the chat. After making this we can 20 | create specific notification types depending on what we want to send. In this 21 | case we wanted to send Announcement objects so we made an announcement 22 | notification. 23 | 24 | ```ruby 25 | module Notifications 26 | class FlowDock 27 | FROM_SOURCE = 'Spencer-Dixon' 28 | EMAIL = 'hello@launchacademy.com' 29 | 30 | def initialize(*args) 31 | @message_args = args.first 32 | @flow = Flowdock::Flow.new( 33 | api_token: token, 34 | source: FROM_SOURCE, 35 | from: { 36 | name: FROM_SOURCE, 37 | address: EMAIL 38 | } 39 | ) 40 | end 41 | 42 | def push_to_chat 43 | @flow.push_to_chat( 44 | content: @message_args[:content], 45 | external_user_name: @message_args[:external_user_name] 46 | ) 47 | end 48 | 49 | protected 50 | def token 51 | if Rails.env.development? || Rails.env.test? 52 | ENV['FLOWDOCK_TEST_TOKEN'] 53 | else 54 | ENV['FLOWDOCK_TOKEN'] 55 | end 56 | end 57 | end 58 | end 59 | ``` 60 | 61 | Announcement Wrapper: 62 | ```ruby 63 | module Notifications 64 | class AnnouncementNotification 65 | 66 | def initialize(announcement) 67 | @announcement = announcement 68 | end 69 | 70 | def dispatch 71 | Notifications::FlowDock.new( 72 | content: content, 73 | external_user_name: external_user_name 74 | ).push_to_chat 75 | end 76 | 77 | private 78 | 79 | def content 80 | "@everyone, #{@announcement.title}: #{@announcement.description}" 81 | end 82 | 83 | def external_user_name 84 | "Launch-Staff" 85 | end 86 | end 87 | end 88 | ``` 89 | 90 | Finally in our controller that creates announcements we can ``#dispatch`` the 91 | announcement on save: 92 | 93 | ```ruby 94 | # announcements_controller.rb 95 | def create 96 | @team = Team.find(params[:team_id]) 97 | @announcement = @team.announcements.build(announcement_params) 98 | 99 | if @announcement.save 100 | Notifications::AnnouncementNotification.new(@announcement).dispatch 101 | flash[:info] = "Added announcement." 102 | redirect_to team_announcements_path(@team) 103 | else 104 | flash[:alert] = "Failed to add announcement." 105 | render :index 106 | end 107 | end 108 | ``` 109 | 110 | There you have it! One way to integrate Flowdock into Rails. 111 | 112 | -------------------------------------------------------------------------------- /image_preview.md: -------------------------------------------------------------------------------- 1 | # Image Preview With Carrierwave 2 | 3 | Had a hard time finding good resources for implementing image preview in Rails 4 | with carrierwave. Here's how I did it: 5 | 6 | ```ruby 7 | # ... rest of the form ... 8 | 9 | # Your carrierwave image uploader 10 |
11 |
12 | 13 | Upload Avatar Image<%= f.file_field :avatar, id: "avatar-upload" %> 14 | 15 | <%= f.hidden_field :avatar_cache %> 16 |
17 | ``` 18 | 19 | This is the javascript that will create an event handler on change for the file 20 | uploading input tag and display the image on the screen. I applied some basic 21 | bootstrap classes to the image. 22 | 23 | ```javascript 24 | $(function() { 25 | function readURL(input) { 26 | if (input.files && input.files[0]) { 27 | var reader = new FileReader(); 28 | 29 | reader.onload = function (e) { 30 | $('#img_prev').attr('src', e.target.result); 31 | } 32 | reader.readAsDataURL(input.files[0]); 33 | } 34 | } 35 | 36 | $("#avatar-upload").change(function(){ 37 | $('#img_prev').removeClass('hidden'); 38 | readURL(this); 39 | }); 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /img/skill-matrix.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/img/skill-matrix.jpg -------------------------------------------------------------------------------- /img/skills.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/img/skills.jpg -------------------------------------------------------------------------------- /markdown.md: -------------------------------------------------------------------------------- 1 | [Setting up Syntax Highlighting with markdown](https://github.com/LaunchAcademy/event_horizon/commit/780627f7937cf0445370f10b595840200c0271f3) 2 | 3 | ## Steps for setting up Markdown in Rails: 4 | 5 | **Step 1**: Write tests: 6 | 7 | This will need to be changed a little bit for whatever you are trying to render 8 | in markdown, this is a good generic test that can be used as a template though. 9 | 10 | ```ruby 11 | scenario 'I can view lessons in markdown' do 12 | lesson = FactoryGirl.create( 13 | :lesson, body: "## Foo\n\nbar\n\n* item 1\n* item 2") 14 | 15 | visit lesson_path(lesson) 16 | 17 | expect(page).to have_content(lesson.title) 18 | expect(page).to have_selector("h2", "Foo") 19 | expect(page).to have_selector("p", "bar") 20 | expect(page).to have_selector("li", "item 1") 21 | expect(page).to have_selector("li", "item 2") 22 | end 23 | ``` 24 | 25 | **Step 2**: Add gems to gemfile and build the Markdown renderer and put in in 26 | your lib folder like so: 27 | 28 | ```ruby 29 | # gemfile 30 | 31 | gem 'redcarpet' 32 | gem 'rouge' 33 | ``` 34 | 35 | Then create the Markdown renderer class: 36 | 37 | ```ruby 38 | # lib/markdown_renderer.rb 39 | require "rouge/plugins/redcarpet" 40 | 41 | class Markdown 42 | def self.render(content) 43 | renderer.render(content) 44 | end 45 | 46 | private 47 | 48 | def self.renderer 49 | Redcarpet::Markdown.new(HighlightingRenderer, 50 | fenced_code_blocks: true, 51 | disable_indented_code_blocks: true) 52 | end 53 | 54 | class HighlightingRenderer < Redcarpet::Render::HTML 55 | include Rouge::Plugins::Redcarpet 56 | end 57 | end 58 | ``` 59 | 60 | **Step 3**: Create lib initializer and add render methods to ApplicationHelper 61 | like so: 62 | 63 | ```ruby 64 | # app/helpers/application_helper.rb 65 | module ApplicationHelper 66 | # other stuff here 67 | 68 | def render_markdown(content) 69 | Markdown.render(content).html_safe 70 | end 71 | end 72 | ``` 73 | 74 | Add initializer 75 | ```ruby 76 | # config/initializers/lib_require.rb 77 | require "markdown_renderer" 78 | ``` 79 | 80 | Now restart the server if you havn't already, since whenever you add a file to 81 | the initializers you will need to restart. You can now use your helpers in the 82 | view to render the markdown like so: 83 | 84 | ```ruby 85 | # app/views/lessons/show.html.haml 86 | %p= render_markdown(@lesson.body) 87 | ``` 88 | 89 | DONE! This markdown renderer example does not safely render markdown so make 90 | sure to create a sanitized version if thats something important to you. 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /omni_auth.md: -------------------------------------------------------------------------------- 1 | ### Using Omni Auth in Rails 2 | 3 | 1. Go to whichever provider you want to use and set up an app/the proper 4 | callbacks. 5 | 6 | Callbacks for google look like: 7 | `https://localhost:3000/auth/google_oauth2/callback` 8 | 9 | 2. Write tests for creating the user. Mock out the auth request that you will 10 | need for creating a user. 11 | 12 | For example: 13 | ```ruby 14 | OmniAuth.config.mock_auth[:google_oauth2] = { 15 | "provider" => "google_oauth2", 16 | "uid" => "123456", 17 | "info" => { 18 | "email" => "spencerdixon@example.com", 19 | "name" => "Spencer Dixon", 20 | "first_name" => "Spencer", 21 | "last_name" => "Dixon", 22 | "image"=>"https://lh6.googleusercontent.com/-AskbC7sGK7A/AAAAAAAAAAI/AAAAAAAAADA/nTDC13Uvcoc/photo.jpg?sz=50" 23 | } 24 | } 25 | ``` 26 | 27 | Here is what the full test looked like: 28 | 29 | ```ruby 30 | require "rails_helper" 31 | 32 | feature "guest creates account" do 33 | 34 | scenario "successful sign up with valid github credentials" do 35 | OmniAuth.config.mock_auth[:google_oauth2] = { 36 | "provider" => "google_oauth2", 37 | "uid" => "123456", 38 | "info" => { 39 | "email" => "spencerdixon@example.com", 40 | "name" => "Spencer Dixon", 41 | "first_name" => "Spencer", 42 | "last_name" => "Dixon", 43 | "image"=>"https://lh6.googleusercontent.com/-AskbC7sGK7A/AAAAAAAAAAI/AAAAAAAAADA/nTDC13Uvcoc/photo.jpg?sz=50" 44 | } 45 | } 46 | 47 | visit root_path 48 | 49 | click_link "Sign In With Google" 50 | 51 | expect(page).to have_content("Signed in as Spencer Dixon") 52 | expect(page).to have_link("Sign Out", session_path) 53 | 54 | expect(User.count).to eq(1) 55 | end 56 | end 57 | ``` 58 | 59 | 3. Add the proper initializer: 60 | 61 | ```ruby 62 | # config/initializer/omniauth.rb 63 | Rails.application.config.middleware.use OmniAuth::Builder do 64 | provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"] 65 | end 66 | ``` 67 | 68 | 4. Make sure to set up test mode in rails_helper 69 | 70 | ```ruby 71 | config.before :each do 72 | OmniAuth.config.test_mode = true 73 | end 74 | ``` 75 | 76 | 5. Set up sessions controller: 77 | 78 | ```ruby 79 | class SessionsController < ApplicationController 80 | def new 81 | redirect_to '/auth/google_oauth2' 82 | end 83 | 84 | def create 85 | user = User.find_or_create_from_omniauth(auth_hash) 86 | session[:user_id] = user.id 87 | redirect_to root_path 88 | end 89 | 90 | def destroy 91 | session[:user_id] = nil 92 | flash[:info] = "Signed out successfully." 93 | redirect_to root_path 94 | end 95 | 96 | def failure 97 | redirect_to root_path, notice: "Unable to sign in." 98 | end 99 | 100 | private 101 | 102 | def auth_hash 103 | request.env["omniauth.auth"] 104 | end 105 | end 106 | ``` 107 | 108 | 6. Fix routes to work properly: 109 | 110 | ```ruby 111 | 112 | Rails.application.routes.draw do 113 | get "auth/:provider/callback", to: "sessions#create" 114 | get "auth/failure", to: "sessions#failure" 115 | 116 | resource :session, only: [:new, :create, :destroy] do 117 | get "failure", on: :member 118 | end 119 | 120 | root "welcome#index" 121 | end 122 | ``` 123 | 124 | 7. Add CLIENT_SECRET and CLIENT_ID to your .env file. Also make a .env.sample 125 | file so others know how to properly set up your app. Add `gem 'dotenv-rails'` 126 | to your gem file to properly load your environment variables that will be used 127 | in the initializer 128 | 129 | 8. Create some session helpers for your views. 130 | 131 | 132 | ```ruby 133 | module SessionHelper 134 | def user_signed_in? 135 | !session[:user_id].nil? 136 | end 137 | 138 | def current_user 139 | User.find_by(id: session[:user_id]) 140 | end 141 | endmodule SessionHelper 142 | def user_signed_in? 143 | !session[:user_id].nil? 144 | end 145 | 146 | def current_user 147 | User.find_by(id: session[:user_id]) 148 | end 149 | end 150 | ``` 151 | 152 | ### Combining Devise with Omni Auth 153 | -------------------------------------------------------------------------------- /omni_auth_devise.md: -------------------------------------------------------------------------------- 1 | ## Using Omni Auth With Devise 2 | 3 | **Step 1**: 4 | 5 | Add gems to gemfile: 6 | 7 | ```ruby 8 | gem 'therubyracer' 9 | gem 'devise' 10 | gem 'omniauth' 11 | gem 'omniauth-github' 12 | ``` 13 | 14 | **Step 2**: Make sure you have a root to your application 15 | 16 | **Step 3**: 17 | 18 | ```ruby 19 | rails g devise:install 20 | rails g devise User 21 | rake db:migrate 22 | ``` 23 | 24 | **Step 4 (optional)**: add authentication to every page on website by creating a 25 | before_action in application controller: 26 | 27 | ```ruby 28 | class ApplicationController < ActionController::Base 29 | protect_from_forgery with: :exception 30 | before_action :authenticate_user! 31 | end 32 | ``` 33 | 34 | **Step 5**: Update user model to support omniauth 35 | 36 | ```ruby 37 | rails g migration add_column_to_users provider uid 38 | rake db:migrate 39 | ``` 40 | 41 | **Step 6**: Get client ID and client Secret from OAuth service provider 42 | and set callback as: http://localhost:3000/users/auth/github/callback 43 | 44 | **Step 7**: Update devise initializer and set up dotenv rails 45 | 46 | ```ruby 47 | gem 'dotenv-rails' 48 | 49 | bundle install 50 | 51 | # go to .gitignore and add: 52 | .env 53 | 54 | # create a .env file with your keys 55 | ``` 56 | 57 | Then update devise initializer with new info 58 | 59 | ```ruby 60 | Devise.setup do |config| 61 | config.omniauth :github, ENV["GITHUB_CLIENT_ID"], ENV["GITHUB_CLIENT_SECRET"] 62 | end 63 | ``` 64 | 65 | **Step 8**: Update user model: 66 | ```ruby 67 | class User < ActiveRecord::Base 68 | devise :database_authenticatable, :registerable, 69 | :recoverable, :rememberable, :trackable, :validatable, 70 | :omniauthable, :omniauth_providers => [:digitalocean] 71 | 72 | def self.from_omniauth(auth) 73 | where(provider: auth.provider, uid: auth.uid).first_or_create do |user| 74 | user.provider = auth.provider 75 | user.uid = auth.uid 76 | user.email = auth.info.email 77 | user.password = Devise.friendly_token[0,20] 78 | end 79 | end 80 | end 81 | ``` 82 | 83 | **Step 9**: Add controller to handle callbacks: 84 | 85 | ```ruby 86 | Rails.application.routes.draw do 87 | devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" } 88 | resources :products 89 | root 'products#index' 90 | end 91 | ``` 92 | 93 | Create the controller: 94 | ```ruby 95 | class CallbacksController < Devise::OmniauthCallbacksController 96 | def digitalocean 97 | @user = User.from_omniauth(request.env["omniauth.auth"]) 98 | sign_in_and_redirect @user 99 | end 100 | end 101 | ``` 102 | 103 | **Step 10**: Restart server and should be good to go! 104 | 105 | **Note**: When using omni auth and devise with multiple providers its important 106 | to check for if someone has already created an account. It's very possible that 107 | a user could sign in with twitter first and github second and then by accidently 108 | create two accounts in your system. To prevent this think about making an 109 | Identity model and using that to check to see if a user already has an identity. 110 | 111 | 112 | -------------------------------------------------------------------------------- /omni_auth_devise/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | !/log/.keep 13 | /tmp 14 | .env 15 | /.env 16 | -------------------------------------------------------------------------------- /omni_auth_devise/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | 4 | gem 'rails', '4.2.1' 5 | gem 'pg' 6 | gem 'sass-rails', '~> 5.0' 7 | gem 'uglifier', '>= 1.3.0' 8 | gem 'jquery-rails' 9 | 10 | gem 'therubyracer' 11 | gem 'devise' 12 | gem 'omniauth' 13 | gem 'omniauth-github' 14 | gem 'dotenv-rails' 15 | 16 | 17 | group :development, :test do 18 | gem 'pry-rails' 19 | end 20 | 21 | -------------------------------------------------------------------------------- /omni_auth_devise/README.rdoc: -------------------------------------------------------------------------------- 1 | == README 2 | 3 | This README would normally document whatever steps are necessary to get the 4 | application up and running. 5 | 6 | Things you may want to cover: 7 | 8 | * Ruby version 9 | 10 | * System dependencies 11 | 12 | * Configuration 13 | 14 | * Database creation 15 | 16 | * Database initialization 17 | 18 | * How to run the test suite 19 | 20 | * Services (job queues, cache servers, search engines, etc.) 21 | 22 | * Deployment instructions 23 | 24 | * ... 25 | 26 | 27 | Please feel free to use a different markup language if you do not plan to run 28 | rake doc:app. 29 | -------------------------------------------------------------------------------- /omni_auth_devise/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require File.expand_path('../config/application', __FILE__) 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /omni_auth_devise/app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/app/assets/images/.keep -------------------------------------------------------------------------------- /omni_auth_devise/app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. 9 | // 10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require jquery 14 | //= require jquery_ujs 15 | //= require_tree . 16 | -------------------------------------------------------------------------------- /omni_auth_devise/app/assets/javascripts/products.js: -------------------------------------------------------------------------------- 1 | // Place all the behaviors and hooks related to the matching controller here. 2 | // All this logic will automatically be available in application.js. 3 | -------------------------------------------------------------------------------- /omni_auth_devise/app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any styles 10 | * defined in the other CSS/SCSS files in this directory. It is generally better to create a new 11 | * file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | -------------------------------------------------------------------------------- /omni_auth_devise/app/assets/stylesheets/products.scss: -------------------------------------------------------------------------------- 1 | // Place all the styles related to the Products controller here. 2 | // They will automatically be included in application.css. 3 | // You can use Sass (SCSS) here: http://sass-lang.com/ 4 | -------------------------------------------------------------------------------- /omni_auth_devise/app/assets/stylesheets/scaffolds.scss: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #fff; 3 | color: #333; 4 | font-family: verdana, arial, helvetica, sans-serif; 5 | font-size: 13px; 6 | line-height: 18px; 7 | } 8 | 9 | p, ol, ul, td { 10 | font-family: verdana, arial, helvetica, sans-serif; 11 | font-size: 13px; 12 | line-height: 18px; 13 | } 14 | 15 | pre { 16 | background-color: #eee; 17 | padding: 10px; 18 | font-size: 11px; 19 | } 20 | 21 | a { 22 | color: #000; 23 | &:visited { 24 | color: #666; 25 | } 26 | &:hover { 27 | color: #fff; 28 | background-color: #000; 29 | } 30 | } 31 | 32 | div { 33 | &.field, &.actions { 34 | margin-bottom: 10px; 35 | } 36 | } 37 | 38 | #notice { 39 | color: green; 40 | } 41 | 42 | .field_with_errors { 43 | padding: 2px; 44 | background-color: red; 45 | display: table; 46 | } 47 | 48 | #error_explanation { 49 | width: 450px; 50 | border: 2px solid red; 51 | padding: 7px; 52 | padding-bottom: 0; 53 | margin-bottom: 20px; 54 | background-color: #f0f0f0; 55 | h2 { 56 | text-align: left; 57 | font-weight: bold; 58 | padding: 5px 5px 5px 15px; 59 | font-size: 12px; 60 | margin: -7px; 61 | margin-bottom: 0px; 62 | background-color: #c00; 63 | color: #fff; 64 | } 65 | ul li { 66 | font-size: 12px; 67 | list-style: square; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /omni_auth_devise/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | # Prevent CSRF attacks by raising an exception. 3 | # For APIs, you may want to use :null_session instead. 4 | protect_from_forgery with: :exception 5 | before_action :authenticate_user! # authenticate all pages in app 6 | end 7 | -------------------------------------------------------------------------------- /omni_auth_devise/app/controllers/callbacks_controller.rb: -------------------------------------------------------------------------------- 1 | class CallbacksController < Devise::OmniauthCallbacksController 2 | def github 3 | @user = User.from_omniauth(request.env["omniauth.auth"]) 4 | sign_in_and_redirect @user 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /omni_auth_devise/app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /omni_auth_devise/app/controllers/products_controller.rb: -------------------------------------------------------------------------------- 1 | class ProductsController < ApplicationController 2 | before_action :set_product, only: [:show, :edit, :update, :destroy] 3 | 4 | # GET /products 5 | def index 6 | @products = Product.all 7 | end 8 | 9 | # GET /products/1 10 | def show 11 | end 12 | 13 | # GET /products/new 14 | def new 15 | @product = Product.new 16 | end 17 | 18 | # GET /products/1/edit 19 | def edit 20 | end 21 | 22 | # POST /products 23 | def create 24 | @product = Product.new(product_params) 25 | 26 | if @product.save 27 | redirect_to @product, notice: 'Product was successfully created.' 28 | else 29 | render :new 30 | end 31 | end 32 | 33 | # PATCH/PUT /products/1 34 | def update 35 | if @product.update(product_params) 36 | redirect_to @product, notice: 'Product was successfully updated.' 37 | else 38 | render :edit 39 | end 40 | end 41 | 42 | # DELETE /products/1 43 | def destroy 44 | @product.destroy 45 | redirect_to products_url, notice: 'Product was successfully destroyed.' 46 | end 47 | 48 | private 49 | # Use callbacks to share common setup or constraints between actions. 50 | def set_product 51 | @product = Product.find(params[:id]) 52 | end 53 | 54 | # Only allow a trusted parameter "white list" through. 55 | def product_params 56 | params.require(:product).permit(:name, :price, :description) 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /omni_auth_devise/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /omni_auth_devise/app/helpers/products_helper.rb: -------------------------------------------------------------------------------- 1 | module ProductsHelper 2 | end 3 | -------------------------------------------------------------------------------- /omni_auth_devise/app/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/app/mailers/.keep -------------------------------------------------------------------------------- /omni_auth_devise/app/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/app/models/.keep -------------------------------------------------------------------------------- /omni_auth_devise/app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/app/models/concerns/.keep -------------------------------------------------------------------------------- /omni_auth_devise/app/models/product.rb: -------------------------------------------------------------------------------- 1 | class Product < ActiveRecord::Base 2 | end 3 | -------------------------------------------------------------------------------- /omni_auth_devise/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ActiveRecord::Base 2 | # Include default devise modules. Others available are: 3 | # :confirmable, :lockable, :timeoutable and :omniauthable 4 | devise :database_authenticatable, :registerable, 5 | :recoverable, :rememberable, :trackable, :validatable, 6 | :omniauthable, :omniauth_providers => [:github] 7 | 8 | def self.from_omniauth(auth) 9 | where(provider: auth.provider, uid: auth.uid).first_or_create do |user| 10 | user.provider = auth.provider 11 | user.uid = auth.uid 12 | user.email = auth.info.email 13 | user.password = Devise.friendly_token[0,20] 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /omni_auth_devise/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | OmniAuthDevise 5 | <%= stylesheet_link_tag 'application', media: 'all' %> 6 | <%= javascript_include_tag 'application' %> 7 | <%= csrf_meta_tags %> 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /omni_auth_devise/app/views/products/_form.html.erb: -------------------------------------------------------------------------------- 1 | <%= form_for(@product) do |f| %> 2 | <% if @product.errors.any? %> 3 |
4 |

<%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:

5 | 6 | 11 |
12 | <% end %> 13 | 14 |
15 | <%= f.label :name %>
16 | <%= f.text_field :name %> 17 |
18 |
19 | <%= f.label :price %>
20 | <%= f.number_field :price %> 21 |
22 |
23 | <%= f.label :description %>
24 | <%= f.text_area :description %> 25 |
26 |
27 | <%= f.submit %> 28 |
29 | <% end %> 30 | -------------------------------------------------------------------------------- /omni_auth_devise/app/views/products/edit.html.erb: -------------------------------------------------------------------------------- 1 |

Editing Product

2 | 3 | <%= render 'form' %> 4 | 5 | <%= link_to 'Show', @product %> | 6 | <%= link_to 'Back', products_path %> 7 | -------------------------------------------------------------------------------- /omni_auth_devise/app/views/products/index.html.erb: -------------------------------------------------------------------------------- 1 |

<%= notice %>

2 | 3 |

Listing Products

4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | <% @products.each do |product| %> 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | <% end %> 26 | 27 |
NamePriceDescription
<%= product.name %><%= product.price %><%= product.description %><%= link_to 'Show', product %><%= link_to 'Edit', edit_product_path(product) %><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %>
28 | 29 |
30 | 31 | <%= link_to 'New Product', new_product_path %> 32 | -------------------------------------------------------------------------------- /omni_auth_devise/app/views/products/new.html.erb: -------------------------------------------------------------------------------- 1 |

New Product

2 | 3 | <%= render 'form' %> 4 | 5 | <%= link_to 'Back', products_path %> 6 | -------------------------------------------------------------------------------- /omni_auth_devise/app/views/products/show.html.erb: -------------------------------------------------------------------------------- 1 |

<%= notice %>

2 | 3 |

4 | Name: 5 | <%= @product.name %> 6 |

7 | 8 |

9 | Price: 10 | <%= @product.price %> 11 |

12 | 13 |

14 | Description: 15 | <%= @product.description %> 16 |

17 | 18 | <%= link_to 'Edit', edit_product_path(@product) %> | 19 | <%= link_to 'Back', products_path %> 20 | -------------------------------------------------------------------------------- /omni_auth_devise/bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /omni_auth_devise/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path("../spring", __FILE__) 4 | rescue LoadError 5 | end 6 | APP_PATH = File.expand_path('../../config/application', __FILE__) 7 | require_relative '../config/boot' 8 | require 'rails/commands' 9 | -------------------------------------------------------------------------------- /omni_auth_devise/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path("../spring", __FILE__) 4 | rescue LoadError 5 | end 6 | require_relative '../config/boot' 7 | require 'rake' 8 | Rake.application.run 9 | -------------------------------------------------------------------------------- /omni_auth_devise/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'pathname' 3 | 4 | # path to your application root. 5 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) 6 | 7 | Dir.chdir APP_ROOT do 8 | # This script is a starting point to setup your application. 9 | # Add necessary setup steps to this file: 10 | 11 | puts "== Installing dependencies ==" 12 | system "gem install bundler --conservative" 13 | system "bundle check || bundle install" 14 | 15 | # puts "\n== Copying sample files ==" 16 | # unless File.exist?("config/database.yml") 17 | # system "cp config/database.yml.sample config/database.yml" 18 | # end 19 | 20 | puts "\n== Preparing database ==" 21 | system "bin/rake db:setup" 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system "rm -f log/*" 25 | system "rm -rf tmp/cache" 26 | 27 | puts "\n== Restarting application server ==" 28 | system "touch tmp/restart.txt" 29 | end 30 | -------------------------------------------------------------------------------- /omni_auth_devise/bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file loads spring without using Bundler, in order to be fast. 4 | # It gets overwritten when you run the `spring binstub` command. 5 | 6 | unless defined?(Spring) 7 | require "rubygems" 8 | require "bundler" 9 | 10 | if match = Bundler.default_lockfile.read.match(/^GEM$.*?^ (?: )*spring \((.*?)\)$.*?^$/m) 11 | Gem.paths = { "GEM_PATH" => [Bundler.bundle_path.to_s, *Gem.path].uniq } 12 | gem "spring", match[1] 13 | require "spring/binstub" 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /omni_auth_devise/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Rails.application 5 | -------------------------------------------------------------------------------- /omni_auth_devise/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | require "rails" 4 | # Pick the frameworks you want: 5 | require "active_model/railtie" 6 | require "active_job/railtie" 7 | require "active_record/railtie" 8 | require "action_controller/railtie" 9 | require "action_mailer/railtie" 10 | require "action_view/railtie" 11 | require "sprockets/railtie" 12 | # require "rails/test_unit/railtie" 13 | 14 | # Require the gems listed in Gemfile, including any gems 15 | # you've limited to :test, :development, or :production. 16 | Bundler.require(*Rails.groups) 17 | 18 | module OmniAuthDevise 19 | class Application < Rails::Application 20 | # Settings in config/environments/* take precedence over those specified here. 21 | # Application configuration should go into files in config/initializers 22 | # -- all .rb files in that directory are automatically loaded. 23 | 24 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 25 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 26 | # config.time_zone = 'Central Time (US & Canada)' 27 | 28 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 29 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 30 | # config.i18n.default_locale = :de 31 | 32 | # Do not swallow errors in after_commit/after_rollback callbacks. 33 | config.active_record.raise_in_transactional_callbacks = true 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /omni_auth_devise/config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | -------------------------------------------------------------------------------- /omni_auth_devise/config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 8.2 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On OS X with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On OS X with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see rails configuration guide 21 | # http://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: 5 23 | 24 | development: 25 | <<: *default 26 | database: omni_auth_devise_development 27 | 28 | # The specified database role being used to connect to postgres. 29 | # To create additional roles in postgres see `$ createuser --help`. 30 | # When left blank, postgres will use the default role. This is 31 | # the same name as the operating system user that initialized the database. 32 | #username: omni_auth_devise 33 | 34 | # The password associated with the postgres role (username). 35 | #password: 36 | 37 | # Connect on a TCP socket. Omitted by default since the client uses a 38 | # domain socket that doesn't need configuration. Windows does not have 39 | # domain sockets, so uncomment these lines. 40 | #host: localhost 41 | 42 | # The TCP port the server listens on. Defaults to 5432. 43 | # If your server runs on a different port number, change accordingly. 44 | #port: 5432 45 | 46 | # Schema search path. The server defaults to $user,public 47 | #schema_search_path: myapp,sharedapp,public 48 | 49 | # Minimum log levels, in increasing order: 50 | # debug5, debug4, debug3, debug2, debug1, 51 | # log, notice, warning, error, fatal, and panic 52 | # Defaults to warning. 53 | #min_messages: notice 54 | 55 | # Warning: The database defined as "test" will be erased and 56 | # re-generated from your development database when you run "rake". 57 | # Do not set this db to the same as development or production. 58 | test: 59 | <<: *default 60 | database: omni_auth_devise_test 61 | 62 | # As with config/secrets.yml, you never want to store sensitive information, 63 | # like your database password, in your source code. If your source code is 64 | # ever seen by anyone, they now have access to your database. 65 | # 66 | # Instead, provide the password as a unix environment variable when you boot 67 | # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database 68 | # for a full rundown on how to provide these environment variables in a 69 | # production deployment. 70 | # 71 | # On Heroku and other platform providers, you may have a full connection URL 72 | # available as an environment variable. For example: 73 | # 74 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 75 | # 76 | # You can use this database configuration with: 77 | # 78 | # production: 79 | # url: <%= ENV['DATABASE_URL'] %> 80 | # 81 | production: 82 | <<: *default 83 | database: omni_auth_devise_production 84 | username: omni_auth_devise 85 | password: <%= ENV['OMNI_AUTH_DEVISE_DATABASE_PASSWORD'] %> 86 | -------------------------------------------------------------------------------- /omni_auth_devise/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /omni_auth_devise/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports and disable caching. 13 | config.consider_all_requests_local = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send. 17 | config.action_mailer.raise_delivery_errors = false 18 | 19 | # Print deprecation notices to the Rails logger. 20 | config.active_support.deprecation = :log 21 | 22 | # Raise an error on page load if there are pending migrations. 23 | config.active_record.migration_error = :page_load 24 | 25 | # Debug mode disables concatenation and preprocessing of assets. 26 | # This option may cause significant delays in view rendering with a large 27 | # number of complex assets. 28 | config.assets.debug = true 29 | 30 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 31 | # yet still be able to expire them through the digest params. 32 | config.assets.digest = true 33 | 34 | # Adds additional error checking when serving assets at runtime. 35 | # Checks for improperly declared sprockets dependencies. 36 | # Raises helpful error messages. 37 | config.assets.raise_runtime_errors = true 38 | 39 | # Raises error for missing translations 40 | # config.action_view.raise_on_missing_translations = true 41 | end 42 | -------------------------------------------------------------------------------- /omni_auth_devise/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Enable Rack::Cache to put a simple HTTP cache in front of your application 18 | # Add `rack-cache` to your Gemfile before enabling this. 19 | # For large-scale production use, consider using a caching reverse proxy like 20 | # NGINX, varnish or squid. 21 | # config.action_dispatch.rack_cache = true 22 | 23 | # Disable serving static files from the `/public` folder by default since 24 | # Apache or NGINX already handles this. 25 | config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? 26 | 27 | # Compress JavaScripts and CSS. 28 | config.assets.js_compressor = :uglifier 29 | # config.assets.css_compressor = :sass 30 | 31 | # Do not fallback to assets pipeline if a precompiled asset is missed. 32 | config.assets.compile = false 33 | 34 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 35 | # yet still be able to expire them through the digest params. 36 | config.assets.digest = true 37 | 38 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 39 | 40 | # Specifies the header that your server uses for sending files. 41 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 42 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 43 | 44 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 45 | # config.force_ssl = true 46 | 47 | # Use the lowest log level to ensure availability of diagnostic information 48 | # when problems arise. 49 | config.log_level = :debug 50 | 51 | # Prepend all log lines with the following tags. 52 | # config.log_tags = [ :subdomain, :uuid ] 53 | 54 | # Use a different logger for distributed setups. 55 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 56 | 57 | # Use a different cache store in production. 58 | # config.cache_store = :mem_cache_store 59 | 60 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 61 | # config.action_controller.asset_host = 'http://assets.example.com' 62 | 63 | # Ignore bad email addresses and do not raise email delivery errors. 64 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 65 | # config.action_mailer.raise_delivery_errors = false 66 | 67 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 68 | # the I18n.default_locale when a translation cannot be found). 69 | config.i18n.fallbacks = true 70 | 71 | # Send deprecation notices to registered listeners. 72 | config.active_support.deprecation = :notify 73 | 74 | # Use default logging formatter so that PID and timestamp are not suppressed. 75 | config.log_formatter = ::Logger::Formatter.new 76 | 77 | # Do not dump schema after migrations. 78 | config.active_record.dump_schema_after_migration = false 79 | end 80 | -------------------------------------------------------------------------------- /omni_auth_devise/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure static file server for tests with Cache-Control for performance. 16 | config.serve_static_files = true 17 | config.static_cache_control = 'public, max-age=3600' 18 | 19 | # Show full error reports and disable caching. 20 | config.consider_all_requests_local = true 21 | config.action_controller.perform_caching = false 22 | 23 | # Raise exceptions instead of rendering exception templates. 24 | config.action_dispatch.show_exceptions = false 25 | 26 | # Disable request forgery protection in test environment. 27 | config.action_controller.allow_forgery_protection = false 28 | 29 | # Tell Action Mailer not to deliver emails to the real world. 30 | # The :test delivery method accumulates sent emails in the 31 | # ActionMailer::Base.deliveries array. 32 | config.action_mailer.delivery_method = :test 33 | 34 | # Randomize the order test cases are executed. 35 | config.active_support.test_order = :random 36 | 37 | # Print deprecation notices to the stderr. 38 | config.active_support.deprecation = :stderr 39 | 40 | # Raises error for missing translations 41 | # config.action_view.raise_on_missing_translations = true 42 | end 43 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | 9 | # Precompile additional assets. 10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. 11 | # Rails.application.config.assets.precompile += %w( search.js ) 12 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.action_dispatch.cookies_serializer = :json 4 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | Devise.setup do |config| 2 | config.mailer_sender = 'mailer@example.com' 3 | 4 | require 'devise/orm/active_record' 5 | config.case_insensitive_keys = [ :email ] 6 | config.strip_whitespace_keys = [ :email ] 7 | config.skip_session_storage = [:http_auth] 8 | config.stretches = Rails.env.test? ? 1 : 10 9 | config.reconfirmable = true 10 | config.expire_all_remember_me_on_sign_out = true 11 | config.password_length = 8..128 12 | config.reset_password_within = 6.hours 13 | config.sign_out_via = :delete 14 | 15 | config.omniauth :github, ENV["GITHUB_CLIENT_ID"], ENV["GITHUB_CLIENT_SECRET"] 16 | end 17 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.session_store :cookie_store, key: '_omni_auth_devise_session' 4 | -------------------------------------------------------------------------------- /omni_auth_devise/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] if respond_to?(:wrap_parameters) 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /omni_auth_devise/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # To learn more, please read the Rails Internationalization guide 20 | # available at http://guides.rubyonrails.org/i18n.html. 21 | 22 | en: 23 | hello: "Hello world" 24 | -------------------------------------------------------------------------------- /omni_auth_devise/config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" } 3 | resources :products 4 | root 'products#index' 5 | end 6 | -------------------------------------------------------------------------------- /omni_auth_devise/config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: fd8eaaccc0f1ee1cfa546c449e676a515f6e5727e41986b378cc78ed4bcc7381f99853ebf88791cc6270985be79f1b5eee10e69e2390e22a3b8572abbe1e3369 15 | 16 | test: 17 | secret_key_base: 779ae115c8158ea5c60ef1521e146f294bf8ce8e179b4294c79fa0ce9a338a7c0e4ff857265263e2fe762960067d04b7b978a80482524d8bb13d7a8aa6d52876 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /omni_auth_devise/db/migrate/20150328151012_create_products.rb: -------------------------------------------------------------------------------- 1 | class CreateProducts < ActiveRecord::Migration 2 | def change 3 | create_table :products do |t| 4 | t.string :name 5 | t.integer :price 6 | t.text :description 7 | 8 | t.timestamps null: false 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /omni_auth_devise/db/migrate/20150328151138_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseCreateUsers < ActiveRecord::Migration 2 | def change 3 | create_table(:users) do |t| 4 | ## Database authenticatable 5 | t.string :email, null: false, default: "" 6 | t.string :encrypted_password, null: false, default: "" 7 | 8 | ## Recoverable 9 | t.string :reset_password_token 10 | t.datetime :reset_password_sent_at 11 | 12 | ## Rememberable 13 | t.datetime :remember_created_at 14 | 15 | ## Trackable 16 | t.integer :sign_in_count, default: 0, null: false 17 | t.datetime :current_sign_in_at 18 | t.datetime :last_sign_in_at 19 | t.inet :current_sign_in_ip 20 | t.inet :last_sign_in_ip 21 | 22 | ## Confirmable 23 | # t.string :confirmation_token 24 | # t.datetime :confirmed_at 25 | # t.datetime :confirmation_sent_at 26 | # t.string :unconfirmed_email # Only if using reconfirmable 27 | 28 | ## Lockable 29 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 30 | # t.string :unlock_token # Only if unlock strategy is :email or :both 31 | # t.datetime :locked_at 32 | 33 | 34 | t.timestamps 35 | end 36 | 37 | add_index :users, :email, unique: true 38 | add_index :users, :reset_password_token, unique: true 39 | # add_index :users, :confirmation_token, unique: true 40 | # add_index :users, :unlock_token, unique: true 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /omni_auth_devise/db/migrate/20150328151341_add_columns_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddColumnsToUsers < ActiveRecord::Migration 2 | def change 3 | add_column :users, :provider, :string 4 | add_column :users, :uid, :string 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /omni_auth_devise/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(version: 20150328151341) do 15 | 16 | # These are extensions that must be enabled in order to support this database 17 | enable_extension "plpgsql" 18 | 19 | create_table "products", force: :cascade do |t| 20 | t.string "name" 21 | t.integer "price" 22 | t.text "description" 23 | t.datetime "created_at", null: false 24 | t.datetime "updated_at", null: false 25 | end 26 | 27 | create_table "users", force: :cascade do |t| 28 | t.string "email", default: "", null: false 29 | t.string "encrypted_password", default: "", null: false 30 | t.string "reset_password_token" 31 | t.datetime "reset_password_sent_at" 32 | t.datetime "remember_created_at" 33 | t.integer "sign_in_count", default: 0, null: false 34 | t.datetime "current_sign_in_at" 35 | t.datetime "last_sign_in_at" 36 | t.inet "current_sign_in_ip" 37 | t.inet "last_sign_in_ip" 38 | t.datetime "created_at" 39 | t.datetime "updated_at" 40 | t.string "provider" 41 | t.string "uid" 42 | end 43 | 44 | add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree 45 | add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree 46 | 47 | end 48 | -------------------------------------------------------------------------------- /omni_auth_devise/db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) 7 | # Mayor.create(name: 'Emanuel', city: cities.first) 8 | -------------------------------------------------------------------------------- /omni_auth_devise/lib/assets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/lib/assets/.keep -------------------------------------------------------------------------------- /omni_auth_devise/lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/lib/tasks/.keep -------------------------------------------------------------------------------- /omni_auth_devise/log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/log/.keep -------------------------------------------------------------------------------- /omni_auth_devise/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /omni_auth_devise/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /omni_auth_devise/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /omni_auth_devise/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/public/favicon.ico -------------------------------------------------------------------------------- /omni_auth_devise/public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | # 3 | # To ban all spiders from the entire site uncomment the next two lines: 4 | # User-agent: * 5 | # Disallow: / 6 | -------------------------------------------------------------------------------- /omni_auth_devise/vendor/assets/javascripts/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/vendor/assets/javascripts/.keep -------------------------------------------------------------------------------- /omni_auth_devise/vendor/assets/stylesheets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/omni_auth_devise/vendor/assets/stylesheets/.keep -------------------------------------------------------------------------------- /password_reset.md: -------------------------------------------------------------------------------- 1 | ## Setting up password reset with Rails 2 | 3 | ### Step 1 - Write your tests 4 | 5 | Before being able to write tests for Mailers we need to add the email_spec gem 6 | to our Gemfile and bundle. 7 | 8 | ```ruby 9 | # Gemfile 10 | group :test do 11 | gem email_spec 12 | end 13 | ``` 14 | Then ``bundle`` 15 | 16 | ```ruby 17 | require 'rails_helper' 18 | 19 | feature 'user resets their password', %Q{ 20 | As an icode user 21 | I want to request an email to reset my password 22 | So that I can regain access to my account 23 | } do 24 | # Acceptance Criteria 25 | # I must specify a valid email address 26 | # If an address is found, that address is emailed with a url to reset a 27 | password 28 | # I must confirm my new password. If the confirmation doesn't 29 | # match the specified password, I get an error message. 30 | # Upon resetting the password, I am authenticated 31 | # The code specified should expire within 24 hours 32 | # If I redeem the url and change the password, the code should expire 33 | 34 | scenario 'successfully sent email upon request', focus: true do 35 | ActionMailer::Base.deliveries = [] 36 | 37 | user = FactoryGirl.create(:classic_user) 38 | visit new_password_reset_path 39 | 40 | fill_in 'Email', with: user.email 41 | click_on 'Reset Password' 42 | 43 | expect(page).to have_content('Email sent with password reset instructions.') 44 | expect(ActionMailer::Base.deliveries.size).to eq(1) 45 | 46 | last_email = ActionMailer::Base.deliveries.last 47 | expect(last_email).to have_subject('Password reset - Launch Academy') 48 | expect(last_email).to deliver_to(user.email) 49 | end 50 | end 51 | ``` 52 | 53 | Next we need to create the Mailers: 54 | ```ruby 55 | # app/mailers/user_mailer.rb 56 | class UserMailer < ActionMailer::Base 57 | default from: "operations@launchacademy.com" 58 | 59 | def password_reset(identity) 60 | @user = identity.user 61 | @identity = identity 62 | mail to: @user.email, subject: "Password reset - Launch Academy" 63 | end 64 | end 65 | ``` 66 | 67 | This creates an email that can be sent using the #password_reset method. An 68 | identity (normally would be a user) can be passed in to customize the email. 69 | 70 | Create the 71 | -------------------------------------------------------------------------------- /polymorphic/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | !/log/.keep 13 | /tmp 14 | -------------------------------------------------------------------------------- /polymorphic/.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --require spec_helper 3 | -------------------------------------------------------------------------------- /polymorphic/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | 4 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 5 | gem 'rails', '4.2.0.rc3' 6 | # Use postgresql as the database for Active Record 7 | gem 'pg' 8 | # Use SCSS for stylesheets 9 | gem 'sass-rails', '~> 5.0' 10 | # Use Uglifier as compressor for JavaScript assets 11 | gem 'uglifier', '>= 1.3.0' 12 | # Use CoffeeScript for .coffee assets and views 13 | gem 'coffee-rails', '~> 4.1.0' 14 | # See https://github.com/sstephenson/execjs#readme for more supported runtimes 15 | # gem 'therubyracer', platforms: :ruby 16 | 17 | # Use jquery as the JavaScript library 18 | gem 'jquery-rails' 19 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 20 | gem 'jbuilder', '~> 2.0' 21 | # bundle exec rake doc:rails generates the API under doc/api. 22 | gem 'sdoc', '~> 0.4.0', group: :doc 23 | 24 | # Use ActiveModel has_secure_password 25 | # gem 'bcrypt', '~> 3.1.7' 26 | 27 | # Use Unicorn as the app server 28 | # gem 'unicorn' 29 | 30 | # Use Capistrano for deployment 31 | # gem 'capistrano-rails', group: :development 32 | 33 | group :development, :test do 34 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 35 | gem 'byebug' 36 | 37 | # Access an IRB console on exception pages or by using <%= console %> in views 38 | gem 'web-console', '~> 2.0' 39 | 40 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 41 | gem 'spring' 42 | gem 'pry-rails' 43 | end 44 | 45 | 46 | gem 'slugged' 47 | gem "font-awesome-sass" 48 | gem 'rspec-rails', group: [:development, :test] 49 | gem 'capybara', group: [:development, :test] 50 | gem 'launchy', group: [:development, :test] 51 | gem 'factory_girl', group: [:development, :test] 52 | gem 'valid_attribute', group: [:development, :test] 53 | gem 'shoulda-matchers', group: [:development, :test], require: false 54 | gem 'devise' 55 | gem 'foundation-rails' 56 | -------------------------------------------------------------------------------- /polymorphic/README.rdoc: -------------------------------------------------------------------------------- 1 | == README 2 | 3 | This README would normally document whatever steps are necessary to get the 4 | application up and running. 5 | 6 | Things you may want to cover: 7 | 8 | * Ruby version 9 | 10 | * System dependencies 11 | 12 | * Configuration 13 | 14 | * Database creation 15 | 16 | * Database initialization 17 | 18 | * How to run the test suite 19 | 20 | * Services (job queues, cache servers, search engines, etc.) 21 | 22 | * Deployment instructions 23 | 24 | * ... 25 | 26 | 27 | Please feel free to use a different markup language if you do not plan to run 28 | rake doc:app. 29 | -------------------------------------------------------------------------------- /polymorphic/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require File.expand_path('../config/application', __FILE__) 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /polymorphic/app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/app/assets/images/.keep -------------------------------------------------------------------------------- /polymorphic/app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. 9 | // 10 | // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require jquery 14 | //= require jquery_ujs 15 | //= require foundation 16 | //= require_tree . 17 | 18 | $(function(){ $(document).foundation(); }); 19 | -------------------------------------------------------------------------------- /polymorphic/app/assets/javascripts/ratings.js: -------------------------------------------------------------------------------- 1 | function buildStarList(starNum){ 2 | var starList = []; 3 | for(var i = 0; i < starNum; i++){ 4 | starList.push(buildStarIcon(i)); 5 | } 6 | 7 | return starList; 8 | } 9 | 10 | function buildStarIcon(index){ 11 | var $icon = $("").addClass("fa fa-star-o"); 12 | 13 | return $("") 14 | .attr("href", "#") 15 | .attr("data-rating", index + 1) 16 | .html($icon); 17 | } 18 | 19 | function handleStarClick(e) { 20 | e.preventDefault(); 21 | 22 | var $trigger = $(e.currentTarget); 23 | var rating = $trigger.attr("data-rating"); 24 | 25 | $trigger.prevAll("a").andSelf().find("i") 26 | .removeClass("fa-star-o") 27 | .addClass("fa-star"); 28 | 29 | $trigger.nextAll("a").find("i") 30 | .removeClass("fa-star") 31 | .addClass("fa-star-o"); 32 | 33 | var $hidden = $('#comment_rating'); 34 | $hidden.val(rating) 35 | } 36 | 37 | function handleStarHover(e) { 38 | var $trigger = $(e.currentTarget); 39 | $trigger.addClass("fa-lg"); 40 | } 41 | 42 | function handleStarHoverOut(e) { 43 | var $trigger = $(e.currentTarget); 44 | $trigger.removeClass("fa-lg"); 45 | } 46 | 47 | $(function(){ 48 | // clear out the rating container 49 | $("#rating-container").html(""); 50 | 51 | // add the link to the container 52 | $("#rating-container").append(buildStarList(5)); 53 | 54 | $("#rating-container a").on("click", handleStarClick); 55 | $("#rating-container a").on("mouseover", handleStarHover); 56 | $("#rating-container a").on("mouseout", handleStarHoverOut); 57 | }); 58 | -------------------------------------------------------------------------------- /polymorphic/app/assets/stylesheets/application.css.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any styles 10 | * defined in the other CSS/SCSS files in this directory. It is generally better to create a new 11 | * file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | *= require foundation_and_overrides 16 | 17 | */ 18 | @import "font-awesome-sprockets"; 19 | @import "font-awesome"; 20 | -------------------------------------------------------------------------------- /polymorphic/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | # Prevent CSRF attacks by raising an exception. 3 | # For APIs, you may want to use :null_session instead. 4 | protect_from_forgery with: :exception 5 | end 6 | -------------------------------------------------------------------------------- /polymorphic/app/controllers/comments_controller.rb: -------------------------------------------------------------------------------- 1 | class CommentsController < ApplicationController 2 | def create 3 | @post = Post.find(params[:post_id]) 4 | @comment = @post.comments.new(comment_params) 5 | 6 | if @comment.save 7 | redirect_to post_path(@post), notice: "Comment Created" 8 | else 9 | render 'posts#show' 10 | end 11 | end 12 | 13 | private 14 | def comment_params 15 | params.require(:comment).permit(:body, :rating) 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /polymorphic/app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /polymorphic/app/controllers/homes_controller.rb: -------------------------------------------------------------------------------- 1 | class HomesController < ApplicationController 2 | def index 3 | @posts = Post.all 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /polymorphic/app/controllers/posts_controller.rb: -------------------------------------------------------------------------------- 1 | class PostsController < ApplicationController 2 | def show 3 | @post = Post.find_using_slug(params[:id]) 4 | @comment = Comment.new 5 | @comments = @post.comments 6 | end 7 | 8 | def new 9 | @post = Post.new 10 | end 11 | 12 | def create 13 | @post = Post.new(post_params) 14 | 15 | if @post.save 16 | redirect_to root_path, notice: "Post successfully created" 17 | else 18 | render 'new' 19 | end 20 | end 21 | 22 | private 23 | def post_params 24 | params.require(:post).permit(:title, :description) 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /polymorphic/app/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/app/mailers/.keep -------------------------------------------------------------------------------- /polymorphic/app/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/app/models/.keep -------------------------------------------------------------------------------- /polymorphic/app/models/comment.rb: -------------------------------------------------------------------------------- 1 | class Comment < ActiveRecord::Base 2 | belongs_to :commentable, polymorphic: true 3 | end 4 | -------------------------------------------------------------------------------- /polymorphic/app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/app/models/concerns/.keep -------------------------------------------------------------------------------- /polymorphic/app/models/post.rb: -------------------------------------------------------------------------------- 1 | class Post < ActiveRecord::Base 2 | is_sluggable :title 3 | has_many :comments, as: :commentable 4 | end 5 | -------------------------------------------------------------------------------- /polymorphic/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ActiveRecord::Base 2 | # Include default devise modules. Others available are: 3 | # :confirmable, :lockable, :timeoutable and :omniauthable 4 | devise :database_authenticatable, :registerable, 5 | :recoverable, :rememberable, :trackable, :validatable 6 | end 7 | -------------------------------------------------------------------------------- /polymorphic/app/views/comments/_comment.html.erb: -------------------------------------------------------------------------------- 1 |
    2 | <%= div_for(comment) do %> 3 |
  • <%= comment.body %> - <%= comment.rating if comment.rating %>
  • 4 | <% end -%> 5 |
6 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/confirmations/new.html.erb: -------------------------------------------------------------------------------- 1 |

Resend confirmation instructions

2 | 3 | <%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> 4 | <%= devise_error_messages! %> 5 | 6 |
7 | <%= f.label :email %>
8 | <%= f.email_field :email, autofocus: true %> 9 |
10 | 11 |
12 | <%= f.submit "Resend confirmation instructions" %> 13 |
14 | <% end %> 15 | 16 | <%= render "devise/shared/links" %> 17 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/mailer/confirmation_instructions.html.erb: -------------------------------------------------------------------------------- 1 |

Welcome <%= @email %>!

2 | 3 |

You can confirm your account email through the link below:

4 | 5 |

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

6 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/mailer/reset_password_instructions.html.erb: -------------------------------------------------------------------------------- 1 |

Hello <%= @resource.email %>!

2 | 3 |

Someone has requested a link to change your password. You can do this through the link below.

4 | 5 |

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

6 | 7 |

If you didn't request this, please ignore this email.

8 |

Your password won't change until you access the link above and create a new one.

9 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/mailer/unlock_instructions.html.erb: -------------------------------------------------------------------------------- 1 |

Hello <%= @resource.email %>!

2 | 3 |

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

4 | 5 |

Click the link below to unlock your account:

6 | 7 |

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

8 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/passwords/edit.html.erb: -------------------------------------------------------------------------------- 1 |

Change your password

2 | 3 | <%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> 4 | <%= devise_error_messages! %> 5 | <%= f.hidden_field :reset_password_token %> 6 | 7 |
8 | <%= f.label :password, "New password" %>
9 | <%= f.password_field :password, autofocus: true, autocomplete: "off" %> 10 |
11 | 12 |
13 | <%= f.label :password_confirmation, "Confirm new password" %>
14 | <%= f.password_field :password_confirmation, autocomplete: "off" %> 15 |
16 | 17 |
18 | <%= f.submit "Change my password" %> 19 |
20 | <% end %> 21 | 22 | <%= render "devise/shared/links" %> 23 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/passwords/new.html.erb: -------------------------------------------------------------------------------- 1 |

Forgot your password?

2 | 3 | <%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> 4 | <%= devise_error_messages! %> 5 | 6 |
7 | <%= f.label :email %>
8 | <%= f.email_field :email, autofocus: true %> 9 |
10 | 11 |
12 | <%= f.submit "Send me reset password instructions" %> 13 |
14 | <% end %> 15 | 16 | <%= render "devise/shared/links" %> 17 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/registrations/edit.html.erb: -------------------------------------------------------------------------------- 1 |

Edit <%= resource_name.to_s.humanize %>

2 | 3 | <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> 4 | <%= devise_error_messages! %> 5 | 6 |
7 | <%= f.label :email %>
8 | <%= f.email_field :email, autofocus: true %> 9 |
10 | 11 | <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> 12 |
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
13 | <% end %> 14 | 15 |
16 | <%= f.label :password %> (leave blank if you don't want to change it)
17 | <%= f.password_field :password, autocomplete: "off" %> 18 |
19 | 20 |
21 | <%= f.label :password_confirmation %>
22 | <%= f.password_field :password_confirmation, autocomplete: "off" %> 23 |
24 | 25 |
26 | <%= f.label :current_password %> (we need your current password to confirm your changes)
27 | <%= f.password_field :current_password, autocomplete: "off" %> 28 |
29 | 30 |
31 | <%= f.submit "Update" %> 32 |
33 | <% end %> 34 | 35 |

Cancel my account

36 | 37 |

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

38 | 39 | <%= link_to "Back", :back %> 40 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/registrations/new.html.erb: -------------------------------------------------------------------------------- 1 |

Sign up

2 | 3 | <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> 4 | <%= devise_error_messages! %> 5 | 6 |
7 | <%= f.label :email %>
8 | <%= f.email_field :email, autofocus: true %> 9 |
10 | 11 |
12 | <%= f.label :password %> 13 | <% if @validatable %> 14 | (<%= @minimum_password_length %> characters minimum) 15 | <% end %>
16 | <%= f.password_field :password, autocomplete: "off" %> 17 |
18 | 19 |
20 | <%= f.label :password_confirmation %>
21 | <%= f.password_field :password_confirmation, autocomplete: "off" %> 22 |
23 | 24 |
25 | <%= f.submit "Sign up" %> 26 |
27 | <% end %> 28 | 29 | <%= render "devise/shared/links" %> 30 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/sessions/new.html.erb: -------------------------------------------------------------------------------- 1 |

Log in

2 | 3 | <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> 4 |
5 | <%= f.label :email %>
6 | <%= f.email_field :email, autofocus: true %> 7 |
8 | 9 |
10 | <%= f.label :password %>
11 | <%= f.password_field :password, autocomplete: "off" %> 12 |
13 | 14 | <% if devise_mapping.rememberable? -%> 15 |
16 | <%= f.check_box :remember_me %> 17 | <%= f.label :remember_me %> 18 |
19 | <% end -%> 20 | 21 |
22 | <%= f.submit "Log in" %> 23 |
24 | <% end %> 25 | 26 | <%= render "devise/shared/links" %> 27 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/shared/_links.html.erb: -------------------------------------------------------------------------------- 1 | <%- if controller_name != 'sessions' %> 2 | <%= link_to "Log in", new_session_path(resource_name) %>
3 | <% end -%> 4 | 5 | <%- if devise_mapping.registerable? && controller_name != 'registrations' %> 6 | <%= link_to "Sign up", new_registration_path(resource_name) %>
7 | <% end -%> 8 | 9 | <%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> 10 | <%= link_to "Forgot your password?", new_password_path(resource_name) %>
11 | <% end -%> 12 | 13 | <%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> 14 | <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
15 | <% end -%> 16 | 17 | <%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> 18 | <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
19 | <% end -%> 20 | 21 | <%- if devise_mapping.omniauthable? %> 22 | <%- resource_class.omniauth_providers.each do |provider| %> 23 | <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %>
24 | <% end -%> 25 | <% end -%> 26 | -------------------------------------------------------------------------------- /polymorphic/app/views/devise/unlocks/new.html.erb: -------------------------------------------------------------------------------- 1 |

Resend unlock instructions

2 | 3 | <%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> 4 | <%= devise_error_messages! %> 5 | 6 |
7 | <%= f.label :email %>
8 | <%= f.email_field :email, autofocus: true %> 9 |
10 | 11 |
12 | <%= f.submit "Resend unlock instructions" %> 13 |
14 | <% end %> 15 | 16 | <%= render "devise/shared/links" %> 17 | -------------------------------------------------------------------------------- /polymorphic/app/views/homes/index.html.erb: -------------------------------------------------------------------------------- 1 |

Polymorphic Associations

2 |

Sign in to create a post that can have comments

3 |

Comments can be rated using stars and JQuery, how cool is that!?

4 | 5 | <% if current_user %> 6 | <%= link_to 'New post', new_post_path, class: 'button info' %> 7 | <% end -%> 8 | 9 | <%= render @posts || "No posts exist" %> 10 | -------------------------------------------------------------------------------- /polymorphic/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Polymorphic 5 | <%= stylesheet_link_tag 'application', media: 'all' %> 6 | <%= csrf_meta_tags %> 7 | 8 | 9 | 10 |
28 | 29 | <%- flash.each do |key, value| -%> 30 |
31 | <%= value %> 32 |
33 | <%- end -%> 34 |
35 | <%= yield %> 36 |
37 | 38 | <%= javascript_include_tag 'application' %> 39 | <%= javascript_tag do %> 40 | $(function(){ 41 | $(document).foundation(); 42 | }); 43 | <% end %> 44 | <%= yield :extra_footer %> 45 | 46 | 47 | -------------------------------------------------------------------------------- /polymorphic/app/views/posts/_post.html.erb: -------------------------------------------------------------------------------- 1 | <%= div_for(post) do %> 2 |

<%= link_to post.title, post_path(post) %>

3 |

<%= post.description %> - Has <%= pluralize(post.comments.count, "comment") %>

4 | <% end -%> 5 | -------------------------------------------------------------------------------- /polymorphic/app/views/posts/new.html.erb: -------------------------------------------------------------------------------- 1 |

New Post

2 | 3 | <%= form_for @post do |f| %> 4 | <%= f.label :title %> 5 | <%= f.text_field :title %> 6 | 7 | <%= f.label :description %> 8 | <%= f.text_field :description %> 9 | 10 | <%= f.submit 'Create post' %> 11 | <% end -%> 12 | 13 | 14 | -------------------------------------------------------------------------------- /polymorphic/app/views/posts/show.html.erb: -------------------------------------------------------------------------------- 1 |

<%= @post.title %>

2 |

<%= @post.description %>

3 | 4 | <%= form_for [@post, @comment] do |f| %> 5 | <%= f.label :body %> 6 | <%= f.text_area :body %> 7 | 8 | <%= f.label "Rate The Post" %> 9 | <%= f.hidden_field :rating %> 10 |
11 |
12 | 13 |

14 | <%= f.submit 'Create comment', class: "button small" %> 15 | <% end -%> 16 | 17 | 18 | <%= render @comments || "No comments exist" %> 19 | -------------------------------------------------------------------------------- /polymorphic/bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /polymorphic/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path("../spring", __FILE__) 4 | rescue LoadError 5 | end 6 | APP_PATH = File.expand_path('../../config/application', __FILE__) 7 | require_relative '../config/boot' 8 | require 'rails/commands' 9 | -------------------------------------------------------------------------------- /polymorphic/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path("../spring", __FILE__) 4 | rescue LoadError 5 | end 6 | require_relative '../config/boot' 7 | require 'rake' 8 | Rake.application.run 9 | -------------------------------------------------------------------------------- /polymorphic/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'pathname' 3 | 4 | # path to your application root. 5 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) 6 | 7 | Dir.chdir APP_ROOT do 8 | # This script is a starting point to setup your application. 9 | # Add necessary setup steps to this file: 10 | 11 | puts "== Installing dependencies ==" 12 | system "gem install bundler --conservative" 13 | system "bundle check || bundle install" 14 | 15 | # puts "\n== Copying sample files ==" 16 | # unless File.exist?("config/database.yml") 17 | # system "cp config/database.yml.sample config/database.yml" 18 | # end 19 | 20 | puts "\n== Preparing database ==" 21 | system "bin/rake db:setup" 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system "rm -f log/*" 25 | system "rm -rf tmp/cache" 26 | 27 | puts "\n== Restarting application server ==" 28 | system "touch tmp/restart.txt" 29 | end 30 | -------------------------------------------------------------------------------- /polymorphic/bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file loads spring without using Bundler, in order to be fast 4 | # It gets overwritten when you run the `spring binstub` command 5 | 6 | unless defined?(Spring) 7 | require "rubygems" 8 | require "bundler" 9 | 10 | if match = Bundler.default_lockfile.read.match(/^GEM$.*?^ (?: )*spring \((.*?)\)$.*?^$/m) 11 | ENV["GEM_PATH"] = ([Bundler.bundle_path.to_s] + Gem.path).join(File::PATH_SEPARATOR) 12 | ENV["GEM_HOME"] = "" 13 | Gem.paths = ENV 14 | 15 | gem "spring", match[1] 16 | require "spring/binstub" 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /polymorphic/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Rails.application 5 | -------------------------------------------------------------------------------- /polymorphic/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | # Pick the frameworks you want: 4 | require "active_model/railtie" 5 | require "active_job/railtie" 6 | require "active_record/railtie" 7 | require "action_controller/railtie" 8 | require "action_mailer/railtie" 9 | require "action_view/railtie" 10 | require "sprockets/railtie" 11 | # require "rails/test_unit/railtie" 12 | 13 | # Require the gems listed in Gemfile, including any gems 14 | # you've limited to :test, :development, or :production. 15 | Bundler.require(*Rails.groups) 16 | 17 | module Polymorphic 18 | class Application < Rails::Application 19 | # Settings in config/environments/* take precedence over those specified here. 20 | # Application configuration should go into files in config/initializers 21 | # -- all .rb files in that directory are automatically loaded. 22 | 23 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 24 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 25 | # config.time_zone = 'Central Time (US & Canada)' 26 | 27 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 28 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 29 | # config.i18n.default_locale = :de 30 | 31 | # Do not swallow errors in after_commit/after_rollback callbacks. 32 | config.active_record.raise_in_transactional_callbacks = true 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /polymorphic/config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | -------------------------------------------------------------------------------- /polymorphic/config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 8.2 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On OS X with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On OS X with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see rails configuration guide 21 | # http://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: 5 23 | 24 | development: 25 | <<: *default 26 | database: polymorphic_development 27 | 28 | # The specified database role being used to connect to postgres. 29 | # To create additional roles in postgres see `$ createuser --help`. 30 | # When left blank, postgres will use the default role. This is 31 | # the same name as the operating system user that initialized the database. 32 | #username: polymorphic 33 | 34 | # The password associated with the postgres role (username). 35 | #password: 36 | 37 | # Connect on a TCP socket. Omitted by default since the client uses a 38 | # domain socket that doesn't need configuration. Windows does not have 39 | # domain sockets, so uncomment these lines. 40 | #host: localhost 41 | 42 | # The TCP port the server listens on. Defaults to 5432. 43 | # If your server runs on a different port number, change accordingly. 44 | #port: 5432 45 | 46 | # Schema search path. The server defaults to $user,public 47 | #schema_search_path: myapp,sharedapp,public 48 | 49 | # Minimum log levels, in increasing order: 50 | # debug5, debug4, debug3, debug2, debug1, 51 | # log, notice, warning, error, fatal, and panic 52 | # Defaults to warning. 53 | #min_messages: notice 54 | 55 | # Warning: The database defined as "test" will be erased and 56 | # re-generated from your development database when you run "rake". 57 | # Do not set this db to the same as development or production. 58 | test: 59 | <<: *default 60 | database: polymorphic_test 61 | 62 | # As with config/secrets.yml, you never want to store sensitive information, 63 | # like your database password, in your source code. If your source code is 64 | # ever seen by anyone, they now have access to your database. 65 | # 66 | # Instead, provide the password as a unix environment variable when you boot 67 | # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database 68 | # for a full rundown on how to provide these environment variables in a 69 | # production deployment. 70 | # 71 | # On Heroku and other platform providers, you may have a full connection URL 72 | # available as an environment variable. For example: 73 | # 74 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 75 | # 76 | # You can use this database configuration with: 77 | # 78 | # production: 79 | # url: <%= ENV['DATABASE_URL'] %> 80 | # 81 | production: 82 | <<: *default 83 | database: polymorphic_production 84 | username: polymorphic 85 | password: <%= ENV['POLYMORPHIC_DATABASE_PASSWORD'] %> 86 | -------------------------------------------------------------------------------- /polymorphic/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /polymorphic/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports and disable caching. 13 | config.consider_all_requests_local = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send. 17 | config.action_mailer.raise_delivery_errors = false 18 | 19 | # Print deprecation notices to the Rails logger. 20 | config.active_support.deprecation = :log 21 | 22 | # Raise an error on page load if there are pending migrations. 23 | config.active_record.migration_error = :page_load 24 | 25 | # Debug mode disables concatenation and preprocessing of assets. 26 | # This option may cause significant delays in view rendering with a large 27 | # number of complex assets. 28 | config.assets.debug = true 29 | 30 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 31 | # yet still be able to expire them through the digest params. 32 | config.assets.digest = true 33 | 34 | # Adds additional error checking when serving assets at runtime. 35 | # Checks for improperly declared sprockets dependencies. 36 | # Raises helpful error messages. 37 | config.assets.raise_runtime_errors = true 38 | 39 | # Raises error for missing translations 40 | # config.action_view.raise_on_missing_translations = true 41 | end 42 | -------------------------------------------------------------------------------- /polymorphic/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Enable Rack::Cache to put a simple HTTP cache in front of your application 18 | # Add `rack-cache` to your Gemfile before enabling this. 19 | # For large-scale production use, consider using a caching reverse proxy like 20 | # NGINX, varnish or squid. 21 | # config.action_dispatch.rack_cache = true 22 | 23 | # Disable Rails's static asset server (Apache or NGINX will already do this). 24 | config.serve_static_assets = false 25 | 26 | # Compress JavaScripts and CSS. 27 | config.assets.js_compressor = :uglifier 28 | # config.assets.css_compressor = :sass 29 | 30 | # Do not fallback to assets pipeline if a precompiled asset is missed. 31 | config.assets.compile = false 32 | 33 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 34 | # yet still be able to expire them through the digest params. 35 | config.assets.digest = true 36 | 37 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 38 | 39 | # Specifies the header that your server uses for sending files. 40 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 41 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 42 | 43 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 44 | # config.force_ssl = true 45 | 46 | # Use the lowest log level to ensure availability of diagnostic information 47 | # when problems arise. 48 | config.log_level = :debug 49 | 50 | # Prepend all log lines with the following tags. 51 | # config.log_tags = [ :subdomain, :uuid ] 52 | 53 | # Use a different logger for distributed setups. 54 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 55 | 56 | # Use a different cache store in production. 57 | # config.cache_store = :mem_cache_store 58 | 59 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 60 | # config.action_controller.asset_host = 'http://assets.example.com' 61 | 62 | # Ignore bad email addresses and do not raise email delivery errors. 63 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 64 | # config.action_mailer.raise_delivery_errors = false 65 | 66 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 67 | # the I18n.default_locale when a translation cannot be found). 68 | config.i18n.fallbacks = true 69 | 70 | # Send deprecation notices to registered listeners. 71 | config.active_support.deprecation = :notify 72 | 73 | # Use default logging formatter so that PID and timestamp are not suppressed. 74 | config.log_formatter = ::Logger::Formatter.new 75 | 76 | # Do not dump schema after migrations. 77 | config.active_record.dump_schema_after_migration = false 78 | end 79 | -------------------------------------------------------------------------------- /polymorphic/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure static asset server for tests with Cache-Control for performance. 16 | config.serve_static_assets = true 17 | config.static_cache_control = 'public, max-age=3600' 18 | 19 | # Show full error reports and disable caching. 20 | config.consider_all_requests_local = true 21 | config.action_controller.perform_caching = false 22 | 23 | # Raise exceptions instead of rendering exception templates. 24 | config.action_dispatch.show_exceptions = false 25 | 26 | # Disable request forgery protection in test environment. 27 | config.action_controller.allow_forgery_protection = false 28 | 29 | # Tell Action Mailer not to deliver emails to the real world. 30 | # The :test delivery method accumulates sent emails in the 31 | # ActionMailer::Base.deliveries array. 32 | config.action_mailer.delivery_method = :test 33 | 34 | # Randomize the order test cases are executed. 35 | config.active_support.test_order = :random 36 | 37 | # Print deprecation notices to the stderr. 38 | config.active_support.deprecation = :stderr 39 | 40 | # Raises error for missing translations 41 | # config.action_view.raise_on_missing_translations = true 42 | end 43 | -------------------------------------------------------------------------------- /polymorphic/config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | 9 | # Precompile additional assets. 10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. 11 | # Rails.application.config.assets.precompile += %w( search.js ) 12 | -------------------------------------------------------------------------------- /polymorphic/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /polymorphic/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.action_dispatch.cookies_serializer = :json 4 | -------------------------------------------------------------------------------- /polymorphic/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /polymorphic/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /polymorphic/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /polymorphic/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.session_store :cookie_store, key: '_polymorphic_session' 4 | -------------------------------------------------------------------------------- /polymorphic/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] if respond_to?(:wrap_parameters) 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /polymorphic/config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | en: 4 | devise: 5 | confirmations: 6 | confirmed: "Your email address has been successfully confirmed." 7 | send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." 8 | send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." 9 | failure: 10 | already_authenticated: "You are already signed in." 11 | inactive: "Your account is not activated yet." 12 | invalid: "Invalid %{authentication_keys} or password." 13 | locked: "Your account is locked." 14 | last_attempt: "You have one more attempt before your account is locked." 15 | not_found_in_database: "Invalid %{authentication_keys} or password." 16 | timeout: "Your session expired. Please sign in again to continue." 17 | unauthenticated: "You need to sign in or sign up before continuing." 18 | unconfirmed: "You have to confirm your email address before continuing." 19 | mailer: 20 | confirmation_instructions: 21 | subject: "Confirmation instructions" 22 | reset_password_instructions: 23 | subject: "Reset password instructions" 24 | unlock_instructions: 25 | subject: "Unlock instructions" 26 | omniauth_callbacks: 27 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"." 28 | success: "Successfully authenticated from %{kind} account." 29 | passwords: 30 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 31 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." 32 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 33 | updated: "Your password has been changed successfully. You are now signed in." 34 | updated_not_active: "Your password has been changed successfully." 35 | registrations: 36 | destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." 37 | signed_up: "Welcome! You have signed up successfully." 38 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." 39 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." 40 | signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." 41 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address." 42 | updated: "Your account has been updated successfully." 43 | sessions: 44 | signed_in: "Signed in successfully." 45 | signed_out: "Signed out successfully." 46 | already_signed_out: "Signed out successfully." 47 | unlocks: 48 | send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." 49 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 50 | unlocked: "Your account has been unlocked successfully. Please sign in to continue." 51 | errors: 52 | messages: 53 | already_confirmed: "was already confirmed, please try signing in" 54 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 55 | expired: "has expired, please request a new one" 56 | not_found: "not found" 57 | not_locked: "was not locked" 58 | not_saved: 59 | one: "1 error prohibited this %{resource} from being saved:" 60 | other: "%{count} errors prohibited this %{resource} from being saved:" 61 | -------------------------------------------------------------------------------- /polymorphic/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # To learn more, please read the Rails Internationalization guide 20 | # available at http://guides.rubyonrails.org/i18n.html. 21 | 22 | en: 23 | hello: "Hello world" 24 | -------------------------------------------------------------------------------- /polymorphic/config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | root 'homes#index' 3 | devise_for :users 4 | resources :posts, only: [:new, :create, :show] 5 | 6 | resources :posts, only: [] do 7 | resources :comments, only: [:create] 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /polymorphic/config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: e27de94c0976ca284a76586e3b59661f2742772f925e7c8393322b491622c08d8df97191bde1f405d0cabfcd9a427675bdf1a7522f95d2ed3e2e6568ed31af70 15 | 16 | test: 17 | secret_key_base: 45993ce3f8626d383d4e9c6b89831348e7a097f43e6c784d6ae8b21407241078c9e531d4cecd1143634600117c71c7aaaf7b46d99d747f76df9f0159845d6cbf 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /polymorphic/db/migrate/20141229145037_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseCreateUsers < ActiveRecord::Migration 2 | def change 3 | create_table(:users) do |t| 4 | ## Database authenticatable 5 | t.string :email, null: false, default: "" 6 | t.string :encrypted_password, null: false, default: "" 7 | 8 | ## Recoverable 9 | t.string :reset_password_token 10 | t.datetime :reset_password_sent_at 11 | 12 | ## Rememberable 13 | t.datetime :remember_created_at 14 | 15 | ## Trackable 16 | t.integer :sign_in_count, default: 0, null: false 17 | t.datetime :current_sign_in_at 18 | t.datetime :last_sign_in_at 19 | t.inet :current_sign_in_ip 20 | t.inet :last_sign_in_ip 21 | 22 | ## Confirmable 23 | # t.string :confirmation_token 24 | # t.datetime :confirmed_at 25 | # t.datetime :confirmation_sent_at 26 | # t.string :unconfirmed_email # Only if using reconfirmable 27 | 28 | ## Lockable 29 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 30 | # t.string :unlock_token # Only if unlock strategy is :email or :both 31 | # t.datetime :locked_at 32 | 33 | 34 | t.timestamps 35 | end 36 | 37 | add_index :users, :email, unique: true 38 | add_index :users, :reset_password_token, unique: true 39 | # add_index :users, :confirmation_token, unique: true 40 | # add_index :users, :unlock_token, unique: true 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /polymorphic/db/migrate/20141229150559_create_posts.rb: -------------------------------------------------------------------------------- 1 | class CreatePosts < ActiveRecord::Migration 2 | def change 3 | create_table :posts do |t| 4 | t.string :title 5 | t.text :description 6 | 7 | t.timestamps null: false 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /polymorphic/db/migrate/20141229153212_add_comments.rb: -------------------------------------------------------------------------------- 1 | class AddComments < ActiveRecord::Migration 2 | def change 3 | create_table :comments do |t| 4 | t.text :body 5 | t.integer :commentable_id 6 | t.string :commentable_type 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /polymorphic/db/migrate/20150113010212_add_column_to_comments.rb: -------------------------------------------------------------------------------- 1 | class AddColumnToComments < ActiveRecord::Migration 2 | def change 3 | add_column :comments, :rating, :integer 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /polymorphic/db/migrate/20150124172857_create_slugged_slugs.rb: -------------------------------------------------------------------------------- 1 | class CreateSluggedSlugs < ActiveRecord::Migration 2 | 3 | def self.up 4 | create_table :slugs do |t| 5 | t.string :scope 6 | t.string :slug 7 | t.integer :record_id 8 | t.datetime :created_at 9 | end 10 | add_index :slugs, [:scope, :slug] 11 | add_index :slugs, [:scope, :record_id] 12 | add_index :slugs, [:scope, :slug, :created_at] 13 | add_index :slugs, [:scope, :record_id, :created_at] 14 | end 15 | 16 | def self.down 17 | drop_table :slugs 18 | end 19 | 20 | end 21 | -------------------------------------------------------------------------------- /polymorphic/db/migrate/20150124173135_add_slugs_to_posts.rb: -------------------------------------------------------------------------------- 1 | class AddSlugsToPosts < ActiveRecord::Migration 2 | def change 3 | add_column :posts, :cached_slug, :string 4 | add_index :posts, :cached_slug 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /polymorphic/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(version: 20150124173135) do 15 | 16 | # These are extensions that must be enabled in order to support this database 17 | enable_extension "plpgsql" 18 | 19 | create_table "comments", force: true do |t| 20 | t.text "body" 21 | t.integer "commentable_id" 22 | t.string "commentable_type" 23 | t.integer "rating" 24 | end 25 | 26 | create_table "posts", force: true do |t| 27 | t.string "title" 28 | t.text "description" 29 | t.datetime "created_at", null: false 30 | t.datetime "updated_at", null: false 31 | t.string "cached_slug" 32 | end 33 | 34 | add_index "posts", ["cached_slug"], name: "index_posts_on_cached_slug", using: :btree 35 | 36 | create_table "slugs", force: true do |t| 37 | t.string "scope" 38 | t.string "slug" 39 | t.integer "record_id" 40 | t.datetime "created_at" 41 | end 42 | 43 | add_index "slugs", ["scope", "record_id", "created_at"], name: "index_slugs_on_scope_and_record_id_and_created_at", using: :btree 44 | add_index "slugs", ["scope", "record_id"], name: "index_slugs_on_scope_and_record_id", using: :btree 45 | add_index "slugs", ["scope", "slug", "created_at"], name: "index_slugs_on_scope_and_slug_and_created_at", using: :btree 46 | add_index "slugs", ["scope", "slug"], name: "index_slugs_on_scope_and_slug", using: :btree 47 | 48 | create_table "users", force: true do |t| 49 | t.string "email", default: "", null: false 50 | t.string "encrypted_password", default: "", null: false 51 | t.string "reset_password_token" 52 | t.datetime "reset_password_sent_at" 53 | t.datetime "remember_created_at" 54 | t.integer "sign_in_count", default: 0, null: false 55 | t.datetime "current_sign_in_at" 56 | t.datetime "last_sign_in_at" 57 | t.inet "current_sign_in_ip" 58 | t.inet "last_sign_in_ip" 59 | t.datetime "created_at" 60 | t.datetime "updated_at" 61 | end 62 | 63 | add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree 64 | add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree 65 | 66 | end 67 | -------------------------------------------------------------------------------- /polymorphic/db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) 7 | # Mayor.create(name: 'Emanuel', city: cities.first) 8 | -------------------------------------------------------------------------------- /polymorphic/lib/assets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/lib/assets/.keep -------------------------------------------------------------------------------- /polymorphic/lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/lib/tasks/.keep -------------------------------------------------------------------------------- /polymorphic/log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/log/.keep -------------------------------------------------------------------------------- /polymorphic/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /polymorphic/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /polymorphic/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /polymorphic/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/public/favicon.ico -------------------------------------------------------------------------------- /polymorphic/public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | # 3 | # To ban all spiders from the entire site uncomment the next two lines: 4 | # User-agent: * 5 | # Disallow: / 6 | -------------------------------------------------------------------------------- /polymorphic/spec/features/user_comments_on_post_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | feature 'User can comment on a post' do 4 | scenario 'successfully' do 5 | user = FactoryGirl.create(:user) 6 | sign_in_as(user) 7 | 8 | post = FactoryGirl.create(:post) 9 | visit root_path 10 | click_on post.title 11 | 12 | expect(page).to have_content(post.title) 13 | expect(page).to have_content(post.description) 14 | 15 | fill_in 'Body', with: 'This is a pretty sweet post' 16 | click_on 'Create comment' 17 | 18 | expect(page).to have_content('This is a pretty sweet post') 19 | expect(page).to have_content('Comment Created') 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /polymorphic/spec/features/user_creates_post_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | feature 'User can create a post' do 4 | scenario 'successfully' do 5 | user = FactoryGirl.create(:user) 6 | sign_in_as(user) 7 | 8 | visit root_path 9 | click_on 'New post' 10 | 11 | fill_in 'Title', with: 'Polymorphic Associations are cool!' 12 | fill_in 'Description', with: 'There pretty cool to learn about' 13 | click_on 'Create post' 14 | 15 | expect(page).to have_content( 'Polymorphic Associations are cool!' ) 16 | expect(page).to have_content( 'There pretty cool to learn about' ) 17 | expect(page).to have_content( 'Post successfully created' ) 18 | end 19 | 20 | scenario 'visitor cannot create post' do 21 | visit root_path 22 | expect(page).to_not have_content('New post') 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /polymorphic/spec/features/user_signs_in_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | feature 'user signs in', %Q{ 4 | As a signed up user 5 | I want to sign in 6 | So that I can regain access to my account 7 | } do 8 | scenario 'specify valid credentials' do 9 | user = FactoryGirl.create(:user) 10 | 11 | visit new_user_session_path 12 | 13 | fill_in 'Email', with: user.email 14 | fill_in 'Password', with: user.password 15 | 16 | click_button 'Log in' 17 | 18 | expect(page).to have_content('Signed in successfully') 19 | expect(page).to have_content('Sign Out') 20 | end 21 | 22 | scenario 'specify invalid credentials' do 23 | visit new_user_session_path 24 | 25 | click_button 'Log in' 26 | expect(page).to have_content('Invalid email or password') 27 | expect(page).to_not have_content('Sign Out') 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /polymorphic/spec/features/user_signs_out_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | feature 'user signs out', %Q{ 4 | As an authenticated user 5 | I want to sign out 6 | So that my identity is forgotten about on the machine I'm using 7 | } do 8 | # Acceptance Criteria 9 | # * If I'm signed in, i have an option to sign out 10 | # * When I opt to sign out, I get a confirmation that my identity has been 11 | # forgotten on the machine I'm using 12 | 13 | scenario 'authenticated user signs out' do 14 | user = FactoryGirl.create(:user) 15 | 16 | visit new_user_session_path 17 | 18 | fill_in 'Email', with: user.email 19 | fill_in 'Password', with: user.password 20 | 21 | click_button 'Log in' 22 | 23 | expect(page).to have_content('Signed in successfully') 24 | 25 | click_link 'Sign Out' 26 | expect(page).to have_content('Signed out successfully') 27 | end 28 | 29 | scenario 'unauthenticated user attempts to sign out' do 30 | visit '/' 31 | expect(page).to_not have_content('Sign Out') 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /polymorphic/spec/features/user_signs_up_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | feature 'user registers', %Q{ 4 | As a visitor 5 | I want to register 6 | So that I can create an account 7 | } do 8 | 9 | # Acceptance Criteria: 10 | # * I must specify a valid email address, 11 | # password, and password confirmation 12 | # * If I don't specify the required information, I am presented with 13 | # an error message 14 | 15 | scenario 'provide valid registration information' do 16 | visit new_user_registration_path 17 | 18 | fill_in 'Email', with: 'john@example.com' 19 | fill_in 'Password', with: 'password' 20 | fill_in 'Password confirmation', with: 'password' 21 | 22 | click_button 'Sign up' 23 | 24 | expect(page).to have_content('Welcome! You have signed up successfully.') 25 | expect(page).to have_content('Sign Out') 26 | end 27 | 28 | scenario 'provide invalid registration information' do 29 | visit new_user_registration_path 30 | 31 | click_button 'Sign up' 32 | expect(page).to have_content("can't be blank") 33 | expect(page).to_not have_content('Sign Out') 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /polymorphic/spec/models/comment_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Comment, :type => :model do 4 | pending "add some examples to (or delete) #{__FILE__}" 5 | end 6 | -------------------------------------------------------------------------------- /polymorphic/spec/models/post_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Post, :type => :model do 4 | pending "add some examples to (or delete) #{__FILE__}" 5 | end 6 | -------------------------------------------------------------------------------- /polymorphic/spec/models/user_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe User, :type => :model do 4 | pending "add some examples to (or delete) #{__FILE__}" 5 | end 6 | -------------------------------------------------------------------------------- /polymorphic/spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | ENV["RAILS_ENV"] ||= 'test' 3 | require 'spec_helper' 4 | require File.expand_path("../../config/environment", __FILE__) 5 | require 'rspec/rails' 6 | require 'shoulda-matchers' 7 | require File.join(File.dirname(__FILE__), 'support/valid_attribute') 8 | require File.join(File.dirname(__FILE__), 'support/factory_girl') 9 | require 'capybara/rspec' 10 | # Add additional requires below this line. Rails is not loaded until this point! 11 | 12 | # Requires supporting ruby files with custom matchers and macros, etc, in 13 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 14 | # run as spec files by default. This means that files in spec/support that end 15 | # in _spec.rb will both be required and run as specs, causing the specs to be 16 | # run twice. It is recommended that you do not name files matching this glob to 17 | # end with _spec.rb. You can configure this pattern with the --pattern 18 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 19 | # 20 | # The following line is provided for convenience purposes. It has the downside 21 | # of increasing the boot-up time by auto-requiring all files in the support 22 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 23 | # require only the support files necessary. 24 | # 25 | Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } 26 | 27 | # Checks for pending migrations before tests are run. 28 | # If you are not using ActiveRecord, you can remove this line. 29 | ActiveRecord::Migration.maintain_test_schema! 30 | 31 | RSpec.configure do |config| 32 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 33 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 34 | 35 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 36 | # examples within a transaction, remove the following line or assign false 37 | # instead of true. 38 | config.use_transactional_fixtures = true 39 | 40 | # RSpec Rails can automatically mix in different behaviours to your tests 41 | # based on their file location, for example enabling you to call `get` and 42 | # `post` in specs under `spec/controllers`. 43 | # 44 | # You can disable this behaviour by removing the line below, and instead 45 | # explicitly tag your specs with their type, e.g.: 46 | # 47 | # RSpec.describe UsersController, :type => :controller do 48 | # # ... 49 | # end 50 | # 51 | # The different available types are documented in the features, such as in 52 | # https://relishapp.com/rspec/rspec-rails/docs 53 | config.infer_spec_type_from_file_location! 54 | config.include AuthenticationHelper 55 | end 56 | -------------------------------------------------------------------------------- /polymorphic/spec/support/authentication_helper.rb: -------------------------------------------------------------------------------- 1 | module AuthenticationHelper 2 | def sign_in_as(user) 3 | visit new_user_session_path 4 | 5 | fill_in 'Email', with: user.email 6 | fill_in 'Password', with: user.password 7 | click_on 'Log in' 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /polymorphic/spec/support/factory_girl.rb: -------------------------------------------------------------------------------- 1 | require 'factory_girl' 2 | 3 | FactoryGirl.define do 4 | factory :user do 5 | sequence(:email) {|n| "user#{n}@example.com" } 6 | password 'password' 7 | password_confirmation 'password' 8 | end 9 | 10 | factory :post do 11 | title 'Polymorphic Associations are so cool!' 12 | description 'This repo is to be used to teach polymorphic associations' 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /polymorphic/spec/support/valid_attribute.rb: -------------------------------------------------------------------------------- 1 | require 'valid_attribute/rspec' 2 | -------------------------------------------------------------------------------- /polymorphic/vendor/assets/javascripts/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/vendor/assets/javascripts/.keep -------------------------------------------------------------------------------- /polymorphic/vendor/assets/stylesheets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/polymorphic/vendor/assets/stylesheets/.keep -------------------------------------------------------------------------------- /rails_gems.md: -------------------------------------------------------------------------------- 1 | ## Gems that make Rails tick: 2 | 3 | **ActiveSupport**: compatibility library, includes methods that change words 4 | from single to plural, or CamelCase to snake_case. Better time/date support than 5 | Ruby standard library. 6 | 7 | **ActiveModel**: hooks features into your models. 8 | 9 | **ActiveRecord**: Object-Relational Mapper (ORM), maps Ruby objects to your SQL 10 | database. Makes working with data way easier. 11 | 12 | **ActionPack**: does the routing. Maps incoming URL to controllers and actions. 13 | Passes instance variables between controllers and views. Can use different 14 | templates like erb or haml. 15 | 16 | **ActionMailer**: used to send out email, has text-based templates and not 17 | regular web-page templates. 18 | 19 | 20 | ### Making Rails/Ruby Gems: 21 | 22 | One common pattern seen in a lot of gems is the ! at the end of method calls 23 | that will raise an error if not executed properly. As I studied the slugged gem 24 | today I found how easy it is to implement those methods in my own gems. Here is 25 | an example that illustrates that very well: 26 | 27 | ```ruby 28 | def find_using_slug(slug) 29 | slug = slug.to_s 30 | value = nil 31 | value ||= find_by_id(slug.to_i) if slug =~ /\A\d+\Z/ 32 | value ||= with_cached_slug(slug).first 33 | value ||= find_using_slug_history(slug) if use_slug_history 34 | value.found_via_slug = slug if value.present? 35 | value 36 | end 37 | 38 | def find_using_slug!(slug) 39 | find_using_slug(slug) or raise ActiveRecord::RecordNotFound 40 | end 41 | ``` 42 | 43 | Essentially all you're doing is calling the original method (the non-bang 44 | version) and adding an ``or raise ActiveRecord::RecordNotFound`` error if 45 | nothing is returned. 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /rake_import.md: -------------------------------------------------------------------------------- 1 | ## How To Create An Import Rake Task 2 | 3 | **Step 1**: Creating tests. Looks something like this: 4 | 5 | This is assuming we have a lesson model and we are trying to import lessons in 6 | markdown for our app. First we are creating a data folder in our spec folder to 7 | store all our sample lessons which we will be importing in our tests. 8 | 9 | ```ruby 10 | describe '.import!' do 11 | let(:sample_lessons_dir) { Rails.root.join("spec/data/sample_lessons") } 12 | 13 | it "creates a new lesson" do 14 | Lesson.import!(File.join(sample_lessons_dir, "expressions")) 15 | 16 | expect(Lesson.count).to eq(1) 17 | 18 | lesson = Lesson.find_by!(slug: "expressions") 19 | expect(lesson.title).to eq("Expressions") 20 | expect(lesson.type).to eq("article") 21 | expect(lesson.description).to eq("bloop.") 22 | expect(lesson.body).to eq("beep boop i'm an expression\n") 23 | expect(lesson.position).to eq(1) 24 | end 25 | end 26 | ``` 27 | 28 | **Step 2**: Build the import method! So first we tell the import method to 29 | fetch all the attributes needed to build a lesson using the .lesson.yml file 30 | 31 | ```ruby 32 | def self.import!(source_dir) 33 | attributes = YAML.load_file(File.join(source_dir, ".lesson.yml")) 34 | end 35 | ``` 36 | 37 | 38 | In this method I am using the source_dir (the name of the directory of the 39 | lesson being uploaded) as the slug for the lessons. Then it's using the 40 | .lesson.yml in order to build all the attributes for a lesson. 41 | 42 | ```ruby 43 | def self.import!(source_dir) 44 | slug = File.basename(source_dir) 45 | 46 | attributes = YAML.load_file(File.join(source_dir, ".lesson.yml")) 47 | content = File.read(File.join(source_dir, "#{slug}.md")) 48 | 49 | lesson = Lesson.find_or_initialize_by(slug: slug) 50 | lesson.slug = slug 51 | lesson.body = content 52 | lesson.title = attributes["title"] 53 | lesson.lesson_type = attributes["type"] 54 | lesson.description = attributes["description"] 55 | 56 | lesson.save! 57 | end 58 | ``` 59 | 60 | Here is what the .lesson.yml looks like: 61 | ```yaml 62 | --- 63 | title: "Variable Assignment" 64 | type: "article" 65 | description: "How to assign variables in Ruby" 66 | tags: "ruby, variables" 67 | --- 68 | ``` 69 | 70 | Finally the last step is to make the actual rake task that will import all the 71 | lessons into the DB. That looks like this: 72 | 73 | ```ruby 74 | namespace :rocket_ship do 75 | desc "Import lessons from the db/lessons directory" 76 | task import_lessons: :environment do 77 | if ENV["LESSON_DIRECTORY"] 78 | curriculum_dir = Rails.root.join(ENV["LESSON_DIRECTORY"]) 79 | Lesson.import_all!(curriculum_dir) 80 | end 81 | end 82 | end 83 | ``` 84 | 85 | **Note**: I also created an import_all! method that looks through whatever the 86 | directory lesson is and imports all of the lessons. 87 | 88 | 89 | -------------------------------------------------------------------------------- /search_feature/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | !/log/.keep 13 | /tmp 14 | -------------------------------------------------------------------------------- /search_feature/.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --require spec_helper 3 | -------------------------------------------------------------------------------- /search_feature/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem "rails", "4.2.0" 4 | 5 | gem "pg" 6 | gem "sass-rails", "~> 5.0" 7 | gem "uglifier", ">= 1.3.0" 8 | gem "jquery-rails" 9 | gem "kaminari" 10 | gem "font-awesome-sass" 11 | 12 | group :development, :test do 13 | gem "spring" 14 | gem "rspec-rails" 15 | gem "capybara" 16 | gem "factory_girl_rails" 17 | end 18 | -------------------------------------------------------------------------------- /search_feature/README.rdoc: -------------------------------------------------------------------------------- 1 | == README 2 | 3 | This README would normally document whatever steps are necessary to get the 4 | application up and running. 5 | 6 | Things you may want to cover: 7 | 8 | * Ruby version 9 | 10 | * System dependencies 11 | 12 | * Configuration 13 | 14 | * Database creation 15 | 16 | * Database initialization 17 | 18 | * How to run the test suite 19 | 20 | * Services (job queues, cache servers, search engines, etc.) 21 | 22 | * Deployment instructions 23 | 24 | * ... 25 | 26 | 27 | Please feel free to use a different markup language if you do not plan to run 28 | rake doc:app. 29 | -------------------------------------------------------------------------------- /search_feature/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require File.expand_path('../config/application', __FILE__) 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /search_feature/app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/app/assets/images/.keep -------------------------------------------------------------------------------- /search_feature/app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. 9 | // 10 | // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require jquery 14 | //= require jquery_ujs 15 | //= require_tree . 16 | -------------------------------------------------------------------------------- /search_feature/app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any styles 10 | * defined in the other CSS/SCSS files in this directory. It is generally better to create a new 11 | * file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | -------------------------------------------------------------------------------- /search_feature/app/controllers/actors_controller.rb: -------------------------------------------------------------------------------- 1 | class ActorsController < ApplicationController 2 | def index 3 | @actors = Actor.page(params[:page]) 4 | end 5 | 6 | def show 7 | @actor = Actor.find(params[:id]) 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /search_feature/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | # Prevent CSRF attacks by raising an exception. 3 | # For APIs, you may want to use :null_session instead. 4 | protect_from_forgery with: :exception 5 | end 6 | -------------------------------------------------------------------------------- /search_feature/app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /search_feature/app/controllers/movies_controller.rb: -------------------------------------------------------------------------------- 1 | class MoviesController < ApplicationController 2 | def index 3 | if params[:query] 4 | @movies = Movie.search(params[:query]) 5 | else 6 | @movies = Movie.all 7 | end 8 | 9 | @movies = @movies.page(params[:page]) 10 | end 11 | 12 | def show 13 | @movie = Movie.find(params[:id]) 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /search_feature/app/controllers/searches_controller.rb: -------------------------------------------------------------------------------- 1 | class SearchesController < ApplicationController 2 | def index 3 | @results = Movie.search(params[:query]) 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /search_feature/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /search_feature/app/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/app/mailers/.keep -------------------------------------------------------------------------------- /search_feature/app/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/app/models/.keep -------------------------------------------------------------------------------- /search_feature/app/models/actor.rb: -------------------------------------------------------------------------------- 1 | class Actor < ActiveRecord::Base 2 | has_many :cast_members 3 | has_many :movies, through: :cast_members 4 | end 5 | -------------------------------------------------------------------------------- /search_feature/app/models/cast_member.rb: -------------------------------------------------------------------------------- 1 | class CastMember < ActiveRecord::Base 2 | belongs_to :movie 3 | belongs_to :actor 4 | end 5 | -------------------------------------------------------------------------------- /search_feature/app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/app/models/concerns/.keep -------------------------------------------------------------------------------- /search_feature/app/models/movie.rb: -------------------------------------------------------------------------------- 1 | class Movie < ActiveRecord::Base 2 | has_many :cast_members 3 | has_many :actors, through: :cast_members 4 | 5 | def self.search(query) 6 | where("plainto_tsquery(?) @@ " + 7 | "to_tsvector('english', title || ' ' || synopsis)", 8 | query) 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /search_feature/app/views/actors/index.html.erb: -------------------------------------------------------------------------------- 1 |

Actors

2 | 3 | 8 | 9 | <%= paginate @actors %> 10 | -------------------------------------------------------------------------------- /search_feature/app/views/actors/show.html.erb: -------------------------------------------------------------------------------- 1 |

<%= @actor.name %>

2 | 3 |

Roles

4 | 5 | 10 | -------------------------------------------------------------------------------- /search_feature/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MovieCatalog 5 | <%= stylesheet_link_tag 'application', media: 'all' %> 6 | <%= javascript_include_tag 'application' %> 7 | <%= csrf_meta_tags %> 8 | 9 | 10 | 11 |

Movie Catalog

12 | 13 | 17 | 18 | <%= yield %> 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /search_feature/app/views/movies/index.html.erb: -------------------------------------------------------------------------------- 1 |

Movies

2 | 3 | <%= form_tag movies_path, method: :get do %> 4 | <%= label_tag :query, "Search" %> 5 | <%= text_field_tag :query %> 6 | <%= submit_tag "Search Movies" %> 7 | <% end %> 8 | 9 | 14 | 15 | <%= paginate @movies %> 16 | -------------------------------------------------------------------------------- /search_feature/app/views/movies/show.html.erb: -------------------------------------------------------------------------------- 1 |

<%= @movie.title %>

2 | 3 |

Actors

4 | 5 | 10 | -------------------------------------------------------------------------------- /search_feature/bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /search_feature/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path("../spring", __FILE__) 4 | rescue LoadError 5 | end 6 | APP_PATH = File.expand_path('../../config/application', __FILE__) 7 | require_relative '../config/boot' 8 | require 'rails/commands' 9 | -------------------------------------------------------------------------------- /search_feature/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path("../spring", __FILE__) 4 | rescue LoadError 5 | end 6 | require_relative '../config/boot' 7 | require 'rake' 8 | Rake.application.run 9 | -------------------------------------------------------------------------------- /search_feature/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'pathname' 3 | 4 | # path to your application root. 5 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) 6 | 7 | Dir.chdir APP_ROOT do 8 | # This script is a starting point to setup your application. 9 | # Add necessary setup steps to this file: 10 | 11 | puts "== Installing dependencies ==" 12 | system "gem install bundler --conservative" 13 | system "bundle check || bundle install" 14 | 15 | # puts "\n== Copying sample files ==" 16 | # unless File.exist?("config/database.yml") 17 | # system "cp config/database.yml.sample config/database.yml" 18 | # end 19 | 20 | puts "\n== Preparing database ==" 21 | system "bin/rake db:setup" 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system "rm -f log/*" 25 | system "rm -rf tmp/cache" 26 | 27 | puts "\n== Restarting application server ==" 28 | system "touch tmp/restart.txt" 29 | end 30 | -------------------------------------------------------------------------------- /search_feature/bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file loads spring without using Bundler, in order to be fast 4 | # It gets overwritten when you run the `spring binstub` command 5 | 6 | unless defined?(Spring) 7 | require "rubygems" 8 | require "bundler" 9 | 10 | if match = Bundler.default_lockfile.read.match(/^GEM$.*?^ (?: )*spring \((.*?)\)$.*?^$/m) 11 | ENV["GEM_PATH"] = ([Bundler.bundle_path.to_s] + Gem.path).join(File::PATH_SEPARATOR) 12 | ENV["GEM_HOME"] = "" 13 | Gem.paths = ENV 14 | 15 | gem "spring", match[1] 16 | require "spring/binstub" 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /search_feature/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Rails.application 5 | -------------------------------------------------------------------------------- /search_feature/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | # Pick the frameworks you want: 4 | require "active_model/railtie" 5 | require "active_job/railtie" 6 | require "active_record/railtie" 7 | require "action_controller/railtie" 8 | require "action_mailer/railtie" 9 | require "action_view/railtie" 10 | require "sprockets/railtie" 11 | # require "rails/test_unit/railtie" 12 | 13 | # Require the gems listed in Gemfile, including any gems 14 | # you've limited to :test, :development, or :production. 15 | Bundler.require(*Rails.groups) 16 | 17 | module MovieCatalog 18 | class Application < Rails::Application 19 | # Settings in config/environments/* take precedence over those specified here. 20 | # Application configuration should go into files in config/initializers 21 | # -- all .rb files in that directory are automatically loaded. 22 | 23 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 24 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 25 | # config.time_zone = 'Central Time (US & Canada)' 26 | 27 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 28 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 29 | # config.i18n.default_locale = :de 30 | 31 | # Do not swallow errors in after_commit/after_rollback callbacks. 32 | config.active_record.raise_in_transactional_callbacks = true 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /search_feature/config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | -------------------------------------------------------------------------------- /search_feature/config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 8.2 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On OS X with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On OS X with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see rails configuration guide 21 | # http://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: 5 23 | 24 | development: 25 | <<: *default 26 | database: movie_catalog_development 27 | 28 | # The specified database role being used to connect to postgres. 29 | # To create additional roles in postgres see `$ createuser --help`. 30 | # When left blank, postgres will use the default role. This is 31 | # the same name as the operating system user that initialized the database. 32 | #username: movie_catalog 33 | 34 | # The password associated with the postgres role (username). 35 | #password: 36 | 37 | # Connect on a TCP socket. Omitted by default since the client uses a 38 | # domain socket that doesn't need configuration. Windows does not have 39 | # domain sockets, so uncomment these lines. 40 | #host: localhost 41 | 42 | # The TCP port the server listens on. Defaults to 5432. 43 | # If your server runs on a different port number, change accordingly. 44 | #port: 5432 45 | 46 | # Schema search path. The server defaults to $user,public 47 | #schema_search_path: myapp,sharedapp,public 48 | 49 | # Minimum log levels, in increasing order: 50 | # debug5, debug4, debug3, debug2, debug1, 51 | # log, notice, warning, error, fatal, and panic 52 | # Defaults to warning. 53 | #min_messages: notice 54 | 55 | # Warning: The database defined as "test" will be erased and 56 | # re-generated from your development database when you run "rake". 57 | # Do not set this db to the same as development or production. 58 | test: 59 | <<: *default 60 | database: movie_catalog_test 61 | 62 | # As with config/secrets.yml, you never want to store sensitive information, 63 | # like your database password, in your source code. If your source code is 64 | # ever seen by anyone, they now have access to your database. 65 | # 66 | # Instead, provide the password as a unix environment variable when you boot 67 | # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database 68 | # for a full rundown on how to provide these environment variables in a 69 | # production deployment. 70 | # 71 | # On Heroku and other platform providers, you may have a full connection URL 72 | # available as an environment variable. For example: 73 | # 74 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 75 | # 76 | # You can use this database configuration with: 77 | # 78 | # production: 79 | # url: <%= ENV['DATABASE_URL'] %> 80 | # 81 | production: 82 | <<: *default 83 | database: movie_catalog_production 84 | username: movie_catalog 85 | password: <%= ENV['MOVIE_CATALOG_DATABASE_PASSWORD'] %> 86 | -------------------------------------------------------------------------------- /search_feature/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /search_feature/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports and disable caching. 13 | config.consider_all_requests_local = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send. 17 | config.action_mailer.raise_delivery_errors = false 18 | 19 | # Print deprecation notices to the Rails logger. 20 | config.active_support.deprecation = :log 21 | 22 | # Raise an error on page load if there are pending migrations. 23 | config.active_record.migration_error = :page_load 24 | 25 | # Debug mode disables concatenation and preprocessing of assets. 26 | # This option may cause significant delays in view rendering with a large 27 | # number of complex assets. 28 | config.assets.debug = true 29 | 30 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 31 | # yet still be able to expire them through the digest params. 32 | config.assets.digest = true 33 | 34 | # Adds additional error checking when serving assets at runtime. 35 | # Checks for improperly declared sprockets dependencies. 36 | # Raises helpful error messages. 37 | config.assets.raise_runtime_errors = true 38 | 39 | # Raises error for missing translations 40 | # config.action_view.raise_on_missing_translations = true 41 | end 42 | -------------------------------------------------------------------------------- /search_feature/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Enable Rack::Cache to put a simple HTTP cache in front of your application 18 | # Add `rack-cache` to your Gemfile before enabling this. 19 | # For large-scale production use, consider using a caching reverse proxy like 20 | # NGINX, varnish or squid. 21 | # config.action_dispatch.rack_cache = true 22 | 23 | # Disable serving static files from the `/public` folder by default since 24 | # Apache or NGINX already handles this. 25 | config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? 26 | 27 | # Compress JavaScripts and CSS. 28 | config.assets.js_compressor = :uglifier 29 | # config.assets.css_compressor = :sass 30 | 31 | # Do not fallback to assets pipeline if a precompiled asset is missed. 32 | config.assets.compile = false 33 | 34 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 35 | # yet still be able to expire them through the digest params. 36 | config.assets.digest = true 37 | 38 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 39 | 40 | # Specifies the header that your server uses for sending files. 41 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 42 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 43 | 44 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 45 | # config.force_ssl = true 46 | 47 | # Use the lowest log level to ensure availability of diagnostic information 48 | # when problems arise. 49 | config.log_level = :debug 50 | 51 | # Prepend all log lines with the following tags. 52 | # config.log_tags = [ :subdomain, :uuid ] 53 | 54 | # Use a different logger for distributed setups. 55 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 56 | 57 | # Use a different cache store in production. 58 | # config.cache_store = :mem_cache_store 59 | 60 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 61 | # config.action_controller.asset_host = 'http://assets.example.com' 62 | 63 | # Ignore bad email addresses and do not raise email delivery errors. 64 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 65 | # config.action_mailer.raise_delivery_errors = false 66 | 67 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 68 | # the I18n.default_locale when a translation cannot be found). 69 | config.i18n.fallbacks = true 70 | 71 | # Send deprecation notices to registered listeners. 72 | config.active_support.deprecation = :notify 73 | 74 | # Use default logging formatter so that PID and timestamp are not suppressed. 75 | config.log_formatter = ::Logger::Formatter.new 76 | 77 | # Do not dump schema after migrations. 78 | config.active_record.dump_schema_after_migration = false 79 | end 80 | -------------------------------------------------------------------------------- /search_feature/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure static file server for tests with Cache-Control for performance. 16 | config.serve_static_files = true 17 | config.static_cache_control = 'public, max-age=3600' 18 | 19 | # Show full error reports and disable caching. 20 | config.consider_all_requests_local = true 21 | config.action_controller.perform_caching = false 22 | 23 | # Raise exceptions instead of rendering exception templates. 24 | config.action_dispatch.show_exceptions = false 25 | 26 | # Disable request forgery protection in test environment. 27 | config.action_controller.allow_forgery_protection = false 28 | 29 | # Tell Action Mailer not to deliver emails to the real world. 30 | # The :test delivery method accumulates sent emails in the 31 | # ActionMailer::Base.deliveries array. 32 | config.action_mailer.delivery_method = :test 33 | 34 | # Randomize the order test cases are executed. 35 | config.active_support.test_order = :random 36 | 37 | # Print deprecation notices to the stderr. 38 | config.active_support.deprecation = :stderr 39 | 40 | # Raises error for missing translations 41 | # config.action_view.raise_on_missing_translations = true 42 | end 43 | -------------------------------------------------------------------------------- /search_feature/config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | 9 | # Precompile additional assets. 10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. 11 | # Rails.application.config.assets.precompile += %w( search.js ) 12 | -------------------------------------------------------------------------------- /search_feature/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /search_feature/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.action_dispatch.cookies_serializer = :json 4 | -------------------------------------------------------------------------------- /search_feature/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /search_feature/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /search_feature/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /search_feature/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.session_store :cookie_store, key: '_movie_catalog_session' 4 | -------------------------------------------------------------------------------- /search_feature/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] if respond_to?(:wrap_parameters) 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /search_feature/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # To learn more, please read the Rails Internationalization guide 20 | # available at http://guides.rubyonrails.org/i18n.html. 21 | 22 | en: 23 | hello: "Hello world" 24 | -------------------------------------------------------------------------------- /search_feature/config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | root "movies#index" 3 | 4 | resources :movies, only: [:index, :show] 5 | resources :actors, only: [:index, :show] 6 | end 7 | -------------------------------------------------------------------------------- /search_feature/config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: 3610f7022ce694d7c1fc8f9f42555aed7acc631855ff273f2340f736e2ff9c007e14e1225d0e98f59a774b6c63d2d8e9c8c5503f05d7e29d9f491ea8700ab405 15 | 16 | test: 17 | secret_key_base: 28422c0f964e5157e629a2bc8f4001cc373e986bb630550395743739bcd68c6a03f70929a394906594fc18ffe710a72dc9de1f8ab8e20a4b3b9d728517d75aef 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /search_feature/db/migrate/20150108143842_create_movies.rb: -------------------------------------------------------------------------------- 1 | class CreateMovies < ActiveRecord::Migration 2 | def change 3 | create_table :movies do |t| 4 | t.string :title, null: false 5 | t.integer :year, null: false 6 | t.text :synopsis 7 | t.integer :rating 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /search_feature/db/migrate/20150108143845_create_actors.rb: -------------------------------------------------------------------------------- 1 | class CreateActors < ActiveRecord::Migration 2 | def change 3 | create_table :actors do |t| 4 | t.string :name, null: false 5 | 6 | t.timestamps 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /search_feature/db/migrate/20150108143849_create_cast_members.rb: -------------------------------------------------------------------------------- 1 | class CreateCastMembers < ActiveRecord::Migration 2 | def change 3 | create_table :cast_members do |t| 4 | t.integer :movie_id, null: false 5 | t.integer :actor_id, null: false 6 | t.string :character 7 | 8 | t.timestamps 9 | end 10 | 11 | add_index :cast_members, :movie_id 12 | add_index :cast_members, :actor_id 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /search_feature/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(version: 20150108143849) do 15 | 16 | # These are extensions that must be enabled in order to support this database 17 | enable_extension "plpgsql" 18 | 19 | create_table "actors", force: :cascade do |t| 20 | t.string "name", limit: 255, null: false 21 | t.datetime "created_at" 22 | t.datetime "updated_at" 23 | end 24 | 25 | create_table "cast_members", force: :cascade do |t| 26 | t.integer "movie_id", null: false 27 | t.integer "actor_id", null: false 28 | t.datetime "created_at" 29 | t.datetime "updated_at" 30 | t.string "character", limit: 255 31 | end 32 | 33 | create_table "movies", force: :cascade do |t| 34 | t.string "title", limit: 255, null: false 35 | t.integer "year", null: false 36 | t.text "synopsis" 37 | t.integer "rating" 38 | t.datetime "created_at" 39 | t.datetime "updated_at" 40 | end 41 | 42 | end 43 | -------------------------------------------------------------------------------- /search_feature/db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) 7 | # Mayor.create(name: 'Emanuel', city: cities.first) 8 | -------------------------------------------------------------------------------- /search_feature/lib/assets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/lib/assets/.keep -------------------------------------------------------------------------------- /search_feature/lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/lib/tasks/.keep -------------------------------------------------------------------------------- /search_feature/log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/log/.keep -------------------------------------------------------------------------------- /search_feature/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /search_feature/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /search_feature/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /search_feature/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/public/favicon.ico -------------------------------------------------------------------------------- /search_feature/public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | # 3 | # To ban all spiders from the entire site uncomment the next two lines: 4 | # User-agent: * 5 | # Disallow: / 6 | -------------------------------------------------------------------------------- /search_feature/spec/factories.rb: -------------------------------------------------------------------------------- 1 | FactoryGirl.define do 2 | factory :movie do 3 | sequence(:title) { |n| "Troll #{n}" } 4 | year 1999 5 | synopsis "Total garbage." 6 | rating 50 7 | end 8 | 9 | factory :actor do 10 | sequence(:name) { |n| "Tom Cruise #{n}" } 11 | end 12 | 13 | factory :cast_members do 14 | movie 15 | actor 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /search_feature/spec/features/search_movies_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | feature "search movies" do 4 | scenario "fill in search form and view results" do 5 | troll = FactoryGirl.create(:movie, title: "Troll 2") 6 | room = FactoryGirl.create(:movie, title: "The Room") 7 | rat_race = FactoryGirl.create(:movie, title: "Rat Race") 8 | troll_hunter = FactoryGirl.create(:movie, title: "Troll Hunter") 9 | 10 | visit "/movies" 11 | fill_in "Search", with: "Troll" 12 | click_button "Search Movies" 13 | 14 | expect(page).to have_link("Troll 2", href: movie_path(troll)) 15 | expect(page).to have_link("Troll Hunter", href: movie_path(troll_hunter)) 16 | expect(page).to_not have_content("The Room") 17 | expect(page).to_not have_content("Rat Race") 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /search_feature/spec/models/movie_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Movie do 4 | describe ".search" do 5 | before :each do 6 | @troll = FactoryGirl.create(:movie, title: "Troll 2") 7 | @room = FactoryGirl.create(:movie, title: "The Room") 8 | @troll_hunter = FactoryGirl.create(:movie, title: "Troll Hunter") 9 | end 10 | 11 | it "searches by title" do 12 | results = Movie.search("Room") 13 | 14 | expect(results).to include(@room) 15 | expect(results).to_not include(@troll) 16 | expect(results).to_not include(@troll_hunter) 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /search_feature/spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | ENV["RAILS_ENV"] ||= 'test' 3 | require 'spec_helper' 4 | require File.expand_path("../../config/environment", __FILE__) 5 | require 'rspec/rails' 6 | # Add additional requires below this line. Rails is not loaded until this point! 7 | 8 | # Requires supporting ruby files with custom matchers and macros, etc, in 9 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 10 | # run as spec files by default. This means that files in spec/support that end 11 | # in _spec.rb will both be required and run as specs, causing the specs to be 12 | # run twice. It is recommended that you do not name files matching this glob to 13 | # end with _spec.rb. You can configure this pattern with the --pattern 14 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 15 | # 16 | # The following line is provided for convenience purposes. It has the downside 17 | # of increasing the boot-up time by auto-requiring all files in the support 18 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 19 | # require only the support files necessary. 20 | # 21 | # Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } 22 | 23 | # Checks for pending migrations before tests are run. 24 | # If you are not using ActiveRecord, you can remove this line. 25 | ActiveRecord::Migration.maintain_test_schema! 26 | 27 | RSpec.configure do |config| 28 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 29 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 30 | 31 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 32 | # examples within a transaction, remove the following line or assign false 33 | # instead of true. 34 | config.use_transactional_fixtures = true 35 | 36 | # RSpec Rails can automatically mix in different behaviours to your tests 37 | # based on their file location, for example enabling you to call `get` and 38 | # `post` in specs under `spec/controllers`. 39 | # 40 | # You can disable this behaviour by removing the line below, and instead 41 | # explicitly tag your specs with their type, e.g.: 42 | # 43 | # RSpec.describe UsersController, :type => :controller do 44 | # # ... 45 | # end 46 | # 47 | # The different available types are documented in the features, such as in 48 | # https://relishapp.com/rspec/rspec-rails/docs 49 | config.infer_spec_type_from_file_location! 50 | end 51 | -------------------------------------------------------------------------------- /search_feature/vendor/assets/javascripts/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/vendor/assets/javascripts/.keep -------------------------------------------------------------------------------- /search_feature/vendor/assets/stylesheets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpencerCDixon/rails-tricks/dd994681ff33c36a82303a00d2500dbd2a3050a5/search_feature/vendor/assets/stylesheets/.keep -------------------------------------------------------------------------------- /tdd-rails.md: -------------------------------------------------------------------------------- 1 | ## Why do TDD? 2 | 3 | * Business requirements 4 | * Make sure it works 5 | * Adding features months later 6 | * Tests act as documentation 7 | * Code is easier to refactor 8 | * Easier to modify/extend code 9 | * Code is written quickly by helping to guide the design decisions 10 | * Validates we are writing code that actually works 11 | * Helps developers hone in on writing code that is absolutely necessary 12 | * Helps establish trust among the team 13 | 14 | 15 | **Acceptance Tests:** High level tests, driven from the user or customer of the 16 | actual web applciation. They would be performing high level actions. 17 | 18 | **Unit Tests**: At a much lower level. Given a state we need to calc the right 19 | sales tax, etc. Isolates small components of the application. 20 | 21 | #### Useful Testing Tools 22 | * Factory Girl 23 | * Shoulda Matchers 24 | * DatabaseCleaner - ensure we have a clean slate between test runs 25 | 26 | **TIP** run rails g to see a list of generators you have available 27 | 28 | Stubs allow you call a method 29 | Mocks expect you to call a method on the object 30 | 31 | 32 | **TIP**: When using database_cleaner you will want to turn off transactional 33 | fixtures 34 | 35 | ```ruby 36 | # DB cleaner configuration from Avdi Grimm 37 | RSpec.configure do |config| 38 | 39 | config.before(:suite) do 40 | DatabaseCleaner.clean_with(:truncation) 41 | end 42 | 43 | config.before(:each) do 44 | DatabaseCleaner.strategy = :transaction 45 | end 46 | 47 | config.before(:each, :js => true) do 48 | DatabaseCleaner.strategy = :truncation 49 | end 50 | 51 | config.before(:each) do 52 | DatabaseCleaner.start 53 | end 54 | 55 | config.after(:each) do 56 | DatabaseCleaner.clean 57 | end 58 | 59 | end 60 | ``` 61 | 62 | Transactional fixtures true will clear the entire test database after the test is 63 | run, however sometimes there are errors where models will get persisted when you 64 | don't want it to. 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /testing.md: -------------------------------------------------------------------------------- 1 | Table Of Contents: 2 | 3 | * [Testing Markdown](#markdown) 4 | * [Testing Mailers](#mailers) 5 | * [Testing Order](#order) 6 | 7 | 8 | 9 | # Markdown 10 | * Create the object that will be rendering markdown and give it some potential tags 11 | * Assert that the proper html tags have been rendered on the page 12 | ```ruby 13 | scenario "view an individual assignment rendered in markdown" do 14 | assignment = FactoryGirl.create( 15 | :assignment, body: "## Foo\n\nbar\n\n* item 1\n* item 2") 16 | 17 | visit assignment_path(assignment) 18 | 19 | expect(page).to have_content(assignment.title) 20 | expect(page).to have_selector("h2", "Foo") 21 | expect(page).to have_selector("p", "bar") 22 | expect(page).to have_selector("li", "item 1") 23 | expect(page).to have_selector("li", "item 2") 24 | end 25 | ``` 26 | 27 | # Mailers 28 | - add `email_spec` to Gemfile and budle 29 | - add these configs to `rails_helper` 30 | 31 | ```ruby 32 | config.include(EmailSpec::Helpers) 33 | config.include(EmailSpec::Matchers) 34 | ``` 35 | 36 | Here is an example acceptance test: 37 | 38 | ```ruby 39 | scenario 'specifies valid information, registers spot' do 40 | #clear out mail deliveries 41 | ActionMailer::Base.deliveries = [] 42 | 43 | prev_count = ParkingRegistration.count 44 | visit '/' 45 | fill_in 'First name', with: 'John' 46 | fill_in 'Last name', with: 'Smith' 47 | fill_in 'Email', with: 'user@example.com' 48 | fill_in 'Spot number', with: 5 49 | click_button 'Register' 50 | 51 | expect(page).to have_content('You registered successfully') 52 | expect(ParkingRegistration.count).to eq(prev_count + 1) 53 | 54 | # upon registering, a confirmation email should be delivered, 55 | # so ActionMailer::Base.deliveries should include the email: 56 | expect(ActionMailer::Base.deliveries.size).to eql(1) 57 | 58 | # the email we just sent should have the proper subject and recipient: 59 | last_email = ActionMailer::Base.deliveries.last 60 | expect(last_email).to have_subject('Parking Confirmation') 61 | expect(last_email).to deliver_to('user@example.com') 62 | end 63 | ``` 64 | 65 | # Order 66 | 67 | How to test that things are in the proper order with capybara: 68 | 69 | Capybara saves the index of all text on the page with a special property called 70 | `page.body.index()` We can use that to assert that some text 71 | appears before or after some other text. 72 | 73 | Here is an example of a test to make sure new posts appear before old posts: 74 | ```ruby 75 | scenario 'newest posts appear at the top' do 76 | old_post = FactoryGirl.create(:post, description: 'old post', created_at: 5.days.ago) 77 | new_post = FactoryGirl.create(:post, description: 'new post') 78 | 79 | visit posts_path 80 | 81 | expect(page.body.index(old_post.description) > 82 | page.body.index(new_post.description)) 83 | end 84 | ``` 85 | -------------------------------------------------------------------------------- /todo.md: -------------------------------------------------------------------------------- 1 | * Make a url shortenerer 2 | * Figure out how to track everytime a link gets clicked 3 | * Implement datepicker into a rails app using foundation and jquery 4 | -------------------------------------------------------------------------------- /warden.md: -------------------------------------------------------------------------------- 1 | # Using Warden 2 | 3 | Warden is a rack middleware that allows you to put hooks in for authentication 4 | with multiple rack applications. Here is how I set up the config for an app 5 | using invitations: 6 | 7 | ```ruby 8 | # config/initializers/warden.rb 9 | 10 | WhiteBoardV2::Application.middleware.use Warden::Manager 11 | 12 | Warden::Manager.after_set_user do |user, auth, opts| 13 | invitation = auth.request.session[:invitation_token] 14 | if invitation.present? 15 | TeamInvitations::Redemption.new(user, invitation).persist! 16 | auth.request.session[:invitation_token] = '' 17 | end 18 | end 19 | ``` 20 | 21 | --------------------------------------------------------------------------------