Ruby on rails RubyonRails基本变量

Ruby on rails RubyonRails基本变量,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在尝试通过玩弄东西来学习RubyonRails,我正在尝试玩弄勇气。然而,我有点困惑来自PHP的背景,我从那里得到回购的东西。我的代码 class RepoController < ApplicationController require "grit" repo = Grit::Repo.new("blahblahblah") def index() puts YAML::dump(repo) end def show() repo.commi

我正在尝试通过玩弄东西来学习RubyonRails,我正在尝试玩弄勇气。然而,我有点困惑来自PHP的背景,我从那里得到回购的东西。我的代码

class RepoController < ApplicationController
  require "grit"
  repo = Grit::Repo.new("blahblahblah")

  def index()
    puts YAML::dump(repo)
  end

  def show()
    repo.commits('master', 10)
    puts repo.inspect
  end
end
class RepoController

我试图转储对象的信息,但似乎无法访问repo变量。我的IDE和Ruby一直在说
未定义的局部变量或方法repo'
,我不知道为什么它不能访问repo变量,它是在类的顶部声明的?

您遇到了范围问题。尝试:

require 'grit'

class RepoController < ApplicationController
  def repo
    @repo ||= Grit::Repo.new("blahblahblah")
  end

  def index()
    puts YAML::dump(repo)
  end

  def show()
    repo.commits('master', 10)
    puts repo.inspect
  end
end
需要“勇气”
类RepoController
您遇到了范围问题。尝试:

require 'grit'

class RepoController < ApplicationController
  def repo
    @repo ||= Grit::Repo.new("blahblahblah")
  end

  def index()
    puts YAML::dump(repo)
  end

  def show()
    repo.commits('master', 10)
    puts repo.inspect
  end
end
需要“勇气”
类RepoController
您的回购变量的定义超出了在索引和显示操作中可见的范围。也许你想要的是这样的:

class RepoController < ApplicationController

  before_filter :set_repo  

  def index()
    puts YAML::dump(@repo)
  end

  def show()
    @repo.commits('master', 10)
    puts @repo.inspect
  end

  def set_repo
    @repo = Grit::Repo.new("blahblahblah")
  end
end
class RepoController

它在加载控制器时创建实例变量。此外,您还需要从那里获取require语句,并将gem“grit”放在gem文件中。

您的repo变量被定义在索引和显示操作中可见的范围之外。也许你想要的是这样的:

class RepoController < ApplicationController

  before_filter :set_repo  

  def index()
    puts YAML::dump(@repo)
  end

  def show()
    @repo.commits('master', 10)
    puts @repo.inspect
  end

  def set_repo
    @repo = Grit::Repo.new("blahblahblah")
  end
end
class RepoController
它在加载控制器时创建实例变量。此外,您还需要将require语句从那里删除,并将gem“grit”放在您的gem文件中