Previously I had been writing “dynamic” lookups like this
# post.rb
class Post < ActiveRecord::Base
STATES = ["draft", "published", "destroyed"]
def state
STATES.sample
end
end
# posts/show.html.erb
...
<dl>
<dt>State</dt>
<dd>
<%= I18n.t("post.states.#{post.state}") %>
</dd>
</dl>
...
Now that I’ve understood scope
I would achieve the same functionality in a cleaner syntax
# post.rb
class Post < ActiveRecord::Base
STATES = ["draft", "published", "destroyed"]
def state
STATES.sample
end
end
# posts/show.html.erb
...
<dl>
<dt>State</dt>
<dd>
<%= I18n.t(post.state, scope: "post.states") %>
</dd>
</dl>
...
A subtle change much much more readable