Skip to content

Commit

Permalink
Add additional_context param to TitleHelper#title
Browse files Browse the repository at this point in the history
The helper previously passed the view assigns to the PageTitle to be used in
internationalised strings. This commit allows the caller to pass a Hash
which will be merged into the view assigns, making it possible to use
additional values in page titles.

* Document additional context parameter in README.
  • Loading branch information
georgebrock authored and calebhearth committed Jul 4, 2014
1 parent 6207192 commit 2175dd4
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ def to_s
end
```

You can pass additional values to the `#title` helper, which can be referenced
in your translations:

```erb
<title><%= title(user_name: current_user.name) %></title>
```

```yaml
en:
titles:
application: '%{user_name} - AppName'
```

## Acknowledgement

Though the idea of translating titles was arrived at seperately, [Brandon
Expand Down
5 changes: 3 additions & 2 deletions app/helpers/title/title_helper.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
module Title
module TitleHelper
def title
PageTitle.new(controller_path, action_name, controller.view_assigns.symbolize_keys).to_s
def title(additional_context = {})
context = controller.view_assigns.merge(additional_context).symbolize_keys
PageTitle.new(controller_path, action_name, context).to_s
end

class PageTitle
Expand Down
13 changes: 11 additions & 2 deletions spec/helpers/title_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,24 @@
stub_rails
stub_controller_and_action(:users, :show)
load_translations(users: { show: '%{name}' })
helper.stub_chain(:controller, :view_assigns, :symbolize_keys).and_return({ name: 'Caleb' })
helper.stub_chain(:controller, :view_assigns).and_return('name' => 'Caleb')

expect(helper.title).to eq('Caleb')
end

it 'can accept a hash of extra context in addition to the view assigns' do
stub_rails
stub_controller_and_action(:users, :show)
load_translations(users: { show: '%{greeting} %{name}' })
helper.stub_chain(:controller, :view_assigns).and_return('name' => 'Caleb')

expect(helper.title(greeting: 'Hello')).to eq('Hello Caleb')
end

def stub_rails
helper.stub(:controller_path).and_return('dashboards')
helper.stub(:action_name)
helper.stub_chain(:controller, :view_assigns, :symbolize_keys).and_return({})
helper.stub_chain(:controller, :view_assigns).and_return({})
Rails.stub_chain(:application, :class).and_return('Dummy::Application')
end

Expand Down

0 comments on commit 2175dd4

Please sign in to comment.