基于当前模型的条件

时间:2013-08-14 07:05:41

标签: ruby-on-rails

我这里有一个名为GmailGcalendar的模型助手

我在2个模型中有多个动作,即gmail.rb和pivotaltracker.rb

它们执行相同的功能,但唯一的区别是连接URL。

在我的lib助手中:

def connection_url
    if API::Pivotaltracker
      'https://www.pivotaltracker.com'
    else
      'https://accounts.google.com'
    end
  end

  def my_connections
    connection_name ||= Faraday.new(:url => "#{connection_url}" , ssl: {verify: false}) do |faraday|
      faraday.request  :url_encoded             # form-encode POST params
      faraday.response :logger                  # log requests to STDOUT
      faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
    end
    puts "@@@@"
    puts connection_url
  end

在我的gmail.rb

def connection
    my_connections
end

和我的pivotaltracker.rb一样

def connection
    my_connections
end

现在他们有不同的连接网址。

Pivotal转到https://www.pivotaltracker.com Gmail转到https://accounts.google.com

但我似乎无法在connection_url动作中使条件有效。

任何变通办法都将受到赞赏。

编辑:

我在这里使用connection_url :(在法拉第区块中)

def my_connections
    connection_name ||= Faraday.new(:url => "#{connection_url}" , ssl: {verify: false}) do |faraday|
      faraday.request  :url_encoded             # form-encode POST params
      faraday.response :logger                  # log requests to STDOUT
      faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
    end
    puts "@@@@"
    puts connection_url
  end

1 个答案:

答案 0 :(得分:0)

您可以将您的lib帮助程序重写为类:

class Connection
  def initialize(url)
    @url = url
  end

  def setup
    connection_name ||= Faraday.new(:url => "@url" , ssl: {verify: false}) do |faraday|
      faraday.request  :url_encoded             # form-encode POST params
      faraday.response :logger                  # log requests to STDOUT
      faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
    end
  end
end

现在,在模型中,您可以使用所需的URL初始化此类,例如:

def connection
    Connection.new("https://accounts.google.com").setup
end

我没有测试这段代码,但它应该有效。