サクサク読めて、アプリ限定の機能も多数!
トップへ戻る
ドラクエ3
rails-bestpractices.com
Before The birth_year method is asking the user for her birthday and then getting the year, and if doesn't have one respond accordingly. def birth_year(user) if user.birthday user.birthday.year else 'No birthday year on file' end end Refactor It should be telling the user to provide a birthday year and expect a coherent response if it has one or not. def birth_year(user) user.birthday.year end cla
Before Using default Ruby Time, Date and DateTime classes will not show times in the time zone specified by config.time_zone in application.rb. Time.zone = "Alaska" Time.now Date.today These show the local time, not the time in Alaska (unless you're already in Alaska). Refactor You should instead use ActiveSupport methods of Time.zone to pickup the Rails time zone. Time.zone.now Time.zone.today Th
Do you always check if ActiveRecord's attributes exist or not by nil?, blank? or present? ? Don't do that again, rails provides a cleaner way by query attribute Bad Smell <% if @user.login.blank? %> <%= link_to 'login', new_session_path %> <% end %> <% if @user.login.present? %> <%= @user.login %> <% end %> It's not bad, but rails provides a cleaner way, we should use query attributes to make code
I would try mapping $stdout and $stdin to some temp variables, assigning a File object to $stdout and $stdin and then restoring originals: original_stdout, original_stdin = $stdout, $stdin $stdout, $stdin = File.new('stdout.log', 'w+'), File.new('stdin.log', 'w+') ... #Do operations with my class ... #Restore original stdout and stdin and close opened files $stdout.close ; $stdin.close $stdout, $s
After many years of rails developing I have finally found satisfying solution to implement enums in rails. Before class Photo < ActiveRecord::Base STATUSES = ['queued', 'new', 'changed', 'removed', 'ready'] def change_status self.status = 'changed' end end In this example we have a list of statuses stored in db as strings. Changing status requires developer to find STATUSES Array and manually type
I don't remember how many times I need to fetch current user in models, such as audit log. Here is a flexible way to set the current user in and fetch the current user from User model. I don't remember how many times I need to fetch the current user in models, for example, I want to log who creates, updates or destroys a post in the Audit model. There is no default way to fetch the current user in
Most developers use AR callbacks after_create/after_update/after_destroy to generate background job, expire cache, etc., but they don't realize these callbacks are still wrapped in database transaction, they probably got unexpected errors on production servers. A relational database, like mysql, provides transactions to wrap several operations in one unit, make them all pass or all fail. All isol
Use anchors (&) and references (*) to merge options allowing your database.yml to not be so repetitive. Obviously you can organize in a way that makes the most sense to your organization but the following is an example where the database and test environments share some config and the production and staging environment share some config. So rather than repeating them you we just tag the first one
Rails mass assignment feature is really useful, but it may be a security issue, it allows an attacker to set any models' attributes you may not expect. To avoid this, we should add attr_accessbile or attr_protected to all models. Last weekend github is hacked because of mass assignment issue, actually it's not rails fault, it's a "junior" develop forgot to add attr_accessible or attr_protected to
It's very common for a rails developer to use time_ago_in_words to display time like "5 minutes ago", but it's too expensive to calculate the time in server side, you should utilize client cpu to calculate the time ago. Rails provides a helper method time_ago_in_words to display the distance between one time and now, like "5 minute ago", it's very useful. Before <%= times_ago_in_words(comment.cre
If you want to generate different urls according to different objects, you should use the polymorphic_path/polymorphic_url to simplify the url generation. Imagine that we have three models, Post, News and Comment. It's common that a post has many comments and a news has many comments, so we define them as class Post < ActiveRecord::Base has_many :comments end class News < ActiveRecord::Base has_ma
Rails developers always pay more attentions on models and controllers refactoring, they don't take care about views modularization, that makes view codes most difficult to maintain. Here I recommend you to use cells gem to write more reuseable, testable and cacheable view codes. Rails developers have a strong idea to write beautiful and high quality ruby codes for models and controllers, they alwa
For reliable formatting of a date/time string in the desired language, use I18n.localise, Time#strftime can cause u unnecessary headache. On different machines, Time#strftime can yield different results, and there is no reliable way to ensure u get the string with the desired language, even after setting the environment variable $LANG, and even recompiling ruby under the desired locale setting. Us
Using the select parameter in Active Record association your can speed up you application about 50% and more. The following example is only focused on the optimization of the association using select, so there are further optimizations for the following examples. Given the models: class Patient < ActiveRecord::Base belongs_to :physician end class Physician < ActiveRecord::Base has_many :patients e
In partial view, we can use the instance variable directly, but it may be confused and make it hard to reuse anywhere, because we don't know exactly which instance variable can be used, so use the local variable in partial with explicitly assignment. Bad Smell class PostsController < ApplicationController def show @post = Post.find(params[:id]) end end <%= render :partial => "sidebar" %> In this e
Sometimes you will build a complex model with params, current_user and other logics in controller, but it makes your controller too big, you should move them into model with a factory method Bad Smell class InvoicesController < ApplicationController def create @invoice = Invoice.new(params[:invoice]) @invoice.address = current_user.address @invoice.phone = current_user.phone @invoice.vip = (@invoi
the routes will become complicated with the growth of your application, contain different namespaces, each with a lot of resources and custom routes, it would be better to split routes into different files according to the namespaces, which makes it easy to maintain the complicated routes. I experienced that with the growth of application, the routes becomes very complicated. The following is a si
Ruby/Rails provides a lot of magic codes, especially for metaprogramming, they are powerful, less codes to implement more functions, but they are not intuition, you should write good comment for your magic codes. Ruby/Rails provides a lot of magic codes, especially for metaprogramming, they are powerful, less codes to implement more functions, but they are not intuition. You may quickly write the
render is one of the often used view helpers, we can pass object, collection or local variables. From rails 2.3, more simplified syntax for render are provided. render is one of the often used view helpers, we use it to extract sub part view. We can pass object, collection or local variables to the partial views. From rails 2.3, more simplified syntax for render are provided that makes render help
Memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs. In rails, you can easily use memoize which is inherited from ActiveSupport::Memoizable. Memoization is an optimization technique used primarily to speed up computer programs by having function call avoid repeat th
There are a few posts told you how to integrate bundler into capistrano, but they are out of date now. After bundler 1.0 released, you can add only one line in capistrano to use bundler. There are a few posts told you how to integrate Bundler into capistrano, the code snippet is as follows namespace :bundler do task :create_symlink, :roles => :app do shared_dir = File.join(shared_path, 'bundle') r
Before in view <% form_for_tag blabal do |f| %> <%= f.text_field_tag :quick, params[:search][:quick] %> <%= select_tag("country", options_for_select([["unassigned" , "0" ]] + Country.to_dropdown, region.country_id), {:name => "search[country]"} ) %> <%= f.submit "Search" %> <% end %> After in controller require 'ostruct' def index @search = OpenStruct.new(params[:search]) end in view <% form_for :
The params hash contains all the data that was submitted from a request. If you modify it, later code won't have access to it. Instead, copy the params hash and modify the copy. Read More
このページを最初にブックマークしてみませんか?
『Rails Best Practices - Rails Best Practices』の新着エントリーを見る
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く