Ben Smith
Ben Smith

Reputation: 819

Ruby on Rails: Passing parameters to a method under class <<self

I'm having a problem passing data from a controller to method under class <<self, for some reason I keep getting the error wrong number of arguments (0 for 1) and cannot work out why I get this error or how I can solve it.

My app/controllers/emails_controller code is:

def create
    # Make a new email
    @email = Email.new(email_params)
    # For the email, store the user id as the id of the user logged in
    @email.user_id = session[:user_id]  
    # store the user id
    @user = session[:user_id]
    # if the email has saved in the database
    if @email.save
        email_to_name = @email.to_name
        # split the email addresses selected by the ";"
        @emails = (email_params[:to]).split("; ")
        # for each email address selected do the following
        @emails.each do |emailaddress|
            # the "to" section of the email is to one email address
            @email.to = emailaddress
            # find who to address the email to using the Contact model
            @email.to_name = address_email_to(email_to_name, @email.prefix, emailaddress)
            # find the contact the user wants to email
            contact = Contact.find_by_email(emailaddress).id
            # generate a unsubscribe token
            @unsubscribe = Rails.application.message_verifier(:unsubscribe).generate(contact)       
            # PASS THE ACCOUNT ID TO THE SMTP SETTINGS METHOD IN MY MAILER
            UserEmails.smtp_settings(@email.account_id)
            # send the email
            UserEmails.send_email(@email, @unsubscribe, @email.logo).deliver_now
        end
        # show the email
        redirect_to @email, notice: 'Email was successfully created.'
    # if not saved
    else
        # go back to the new email page
        redirect 'new'
    end
  end

private 
def email_params 
    res = params.require(:email).permit(:account_id, :cc, :bcc, :subject, :greeting, :to_name, :prefix, :message, :from_name, :logo, to: []) 
    res[:to] = res[:to].join('; ')
    res 
end

And my app/mailers/user_emails.rb is:

class UserEmails < ApplicationMailer

    if Rails.env.development?
        class <<self
          def smtp_settings(account)
            options = YAML.load_file("#{Rails.root}/config/mailers.yml")[Rails.env]['send_email']
            @@smtp_settings = {
              :address              => 'smtp.gmail.com',
              :port                 => 587,
              :domain               => 'my-domain.com',
              :authentication       => 'plain',
              # FIND THE USER-NAME IN THE ACCOUNT MODEL
              :user_name            => Account.find_by_id(account).email,
              :password             => 'my password', 
            }
          end
        end
    end
    def send_email(email, unsubscribe, logo)
        @url  = 'http://localhost:3000/users/login'
        @email = email
        @unsubscribe = unsubscribe
        @logo = logo
        mail(from: "#{@email.from_name} <#{@email.account.email}>", to: @email.to, cc: @email.cc, bcc: @email.bcc, subject: @email.subject, message: @email.message)
    end
end

The log reads:

Started POST "/emails" for ::1 at 2016-09-09 11:11:15 +0100
Processing by EmailsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"rCvqJpUNAMker3u6R5sOLjP317oN33t7LSAbJoul1nNkfRt/WwJYT+4vS/fmNW37/XzSOREqafIj/Dqf1k330Q==", "email"=>{"from_name"=>"Ben Smith", "account_id"=>"30", "to"=>["[email protected]", ""], "logo"=>"", "subject"=>"", "greeting"=>"No Greeting", "to_name"=>"No Name", "prefix"=>"No", "message"=>""}, "commit"=>"Create Email"}
  [1m[35m (0.0ms)[0m  begin transaction
  [1m[36mSQL (1.0ms)[0m  [1mINSERT INTO "emails" ("account_id", "subject", "greeting", "to_name", "prefix", "message", "from_name", "logo", "to", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)[0m  [["account_id", 30], ["subject", ""], ["greeting", ""], ["to_name", "No Name"], ["prefix", "No"], ["message", ""], ["from_name", "Ben Smith"], ["logo", ""], ["to", "[email protected]; "], ["user_id", 2], ["created_at", "2016-09-09 10:11:15.382459"], ["updated_at", "2016-09-09 10:11:15.382459"]]
  [1m[35m (205.0ms)[0m  commit transaction
  [1m[36mContact Load (0.0ms)[0m  [1mSELECT  "contacts".* FROM "contacts" WHERE "contacts"."email" = ? LIMIT 1[0m  [["email", "[email protected]"]]
  [1m[35mAccount Load (0.0ms)[0m  SELECT  "accounts".* FROM "accounts" WHERE "accounts"."id" = ? LIMIT 1  [["id", 30]]

UserEmails#send_email: processed outbound mail in 6.0ms
Completed 500 Internal Server Error in 234ms (ActiveRecord: 206.0ms)

ArgumentError (wrong number of arguments (0 for 1)):
  app/mailers/user_emails.rb:5:in `smtp_settings'
  app/mailers/user_emails.rb:34:in `send_email'
  app/controllers/emails_controller.rb:58:in `block in create'
  app/controllers/emails_controller.rb:46:in `each'
  app/controllers/emails_controller.rb:46:in `create'


  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (4.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (1470.1ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (13.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (1370.1ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (3191.2ms)

For background information, what I'm trying to do is change the SMTP server settings per each logged in user, and I'm testing whether this would work by changing the user-name setting - if this works then I intend to also configure the other smtp settings for each user. E.g. the system stores an address, port, domain, authentication user-name, and password for each user, when user 1 sends an email these are all configured as per their settings, when user 2 sends an email these are configured as per their settings. I am only including user-name as a test at the minute to see if this theory would work.

Can someone help me solve my issue?

Upvotes: 3

Views: 650

Answers (2)

Michał Młoźniak
Michał Młoźniak

Reputation: 5556

smtp_settings method is already defined in ActionMailer as method with 0 parameters. You redefined it as a method with 1 parameter. This causes current error app/mailers/user_emails.rb:34:insend_email'.mailmethod is callingsmtp_settings` without any parameters. One solution is to just rename your method to something that won't conflict with already existing methods available in ActionMailer. But I think this approach is not good.

What you can do is to pass your SMTP settings to mail method as delivery_method_options hash. Here is an example

def send_email(email, unsubscribe, logo)
  @url  = 'http://localhost:3000/users/login'
  @email = email
  @unsubscribe = unsubscribe
  @logo = logo

  account = Account.find_by_id(email.account)
  # You can change here all SMTP settings
  delivery_method_options = {
    :address              => 'smtp.gmail.com',
    :port                 => 587,
    :domain               => 'my-domain.com',
    :authentication       => 'plain',
    :user_name            => account.email,
    :password             => 'my password', 
  }

  mail(
    from: "#{@email.from_name} <#{@email.account.email}>",
    to: @email.to,
    cc: @email.cc,
    bcc: @email.bcc,
    subject: @email.subject,
    message: @email.message,
    delivery_method_options: delivery_method_options
  )
end

Upvotes: 3

Apoorv Shrivastava
Apoorv Shrivastava

Reputation: 1

I don't if i am wrong but in your controller code @email = Email.new(email_params)

you have not defined your email_params as i suppose its you defined params.

Upvotes: -2

Related Questions