I want to create custom class that will generate notifications for users. My question is: how to generate link to resource in notification text via link_to
Rails helper?
What I alreay tried:
Followed instructions from this and similar answers like "How to use link_to
in Model": included ActionView::Helpers::UrlHelper
and Rails.application.routes.url_helpers
into Maker
class and had follwing error, that appears in the create_text
method when I try to use link_to
:
EmployeesControllerTest#test_company_vacancy_daily:
NameError: undefined local variable or method `controller' for #<Notifies::Maker:0x000000069ae218>
/usr/local/rvm/gems/ruby-2.2.5/gems/actionview-5.0.0.1/lib/action_view/routing_url_for.rb:132:in `optimize_routes_generation?'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionpack-5.0.0.1/lib/action_dispatch/routing/route_set.rb:192:in `optimize_routes_generation?'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionpack-5.0.0.1/lib/action_dispatch/routing/route_set.rb:172:in `call'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionpack-5.0.0.1/lib/action_dispatch/routing/route_set.rb:295:in `block (2 levels) in define_url_helper'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionpack-5.0.0.1/lib/action_dispatch/routing/polymorphic_routes.rb:262:in `handle_model_call'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionview-5.0.0.1/lib/action_view/routing_url_for.rb:116:in `url_for'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionview-5.0.0.1/lib/action_view/helpers/url_helper.rb:196:in `link_to'
/app/lib/notifies.rb:32:in `block in create_text'
/app/lib/notifies.rb:32:in `map!'
/app/lib/notifies.rb:32:in `create_text'
/app/lib/notifies.rb:38:in `run'
/app/test/controllers/notifications_test.rb:167:in `block (2 levels) in <class:EmployeesControllerTest>'
/usr/local/rvm/gems/ruby-2.2.5/gems/activesupport-5.0.0.1/lib/active_support/testing/assertions.rb:71:in `assert_difference'
/app/test/controllers/notifications_test.rb:166:in `block in <class:EmployeesControllerTest>'
And my code is:
module Notifies
class Maker
include ActionView::Helpers::UrlHelper
include Rails.application.routes.url_helpers
def initialize(model, kind)
@model = model
@kind = kind
case @model.class.to_s
when 'Company'
@to = @model.admin
when 'Employee'
@to = @model
end
end
def build_list
present = Time.now.utc
past = present - 24.hours
popularities = Popularity.where(to: @model.entity.id).select do |e|
e.updated_at.utc.between?(past, present)
end
popularities.map! { |p| p.from_entity.turn }
end
def create_text(popularities = build_list)
text = 'Those users interested in your contacts: '
popularities.map! { |p| link_to p.full_name, p }
text + popularities.join(', ')
end
def run
popularities = build_list
text = create_text(popularities)
@to.notify(kind: @kind, text: text) if popularities.any?
end
end
end