【发布时间】:2012-03-20 10:14:25
【问题描述】:
** 使用 Rails:3.2.1,Ruby:ruby 1.9.3p0(2011-10-30 修订版 33570)[i686-linux] **
在我的模块中,我有一个私有实例方法 (get_tables_of_random_words) 和 一个模块函数(get_random_word)。
我正在从我的 Rails 控制器调用模块函数,它可以正常工作。 但是,当我调用模块的私有实例方法时,它也会毫无问题地被调用。
任何人都可以解释这种行为背后的原因以及如何实现 我想要的功能。我不想获得我模块的私有实例方法 从包含我的模块的类中调用。我的私有实例方法是一个实用方法 仅需要从模块内部工作。
Util::RandomWordsUtil
module Util
module RandomWordsUtil
def get_tables_of_random_words
# Implementation here
end
private :get_tables_of_random_words
module_function
def get_random_word
# invoke get_tables_of_random_words
end
end
end
GamesController(脚手架生成控制器-自定义)
class GamesController < ApplicationController
include Util::RandomWordsUtil
# GET /games
# GET /games.json
def index
end
def play
@game = Game.find(params[:id])
@random_word = get_random_word # This is a module_function
@random_table = get_tables_of_random_words # This I have marked as private in my module still it gets invoked!
# Render action show
render "show"
end
# GET /games/1
# GET /games/1.json
def show
end
# GET /games/new
# GET /games/new.json
def new
end
# GET /games/1/edit
def edit
end
# POST /games
# POST /games.json
def create
end
# PUT /games/1
# PUT /games/1.json
def update
end
# DELETE /games/1
# DELETE /games/1.json
def destroy
end
end
以下是我尝试过但效果不佳的方法。 参考:Private module methods in Ruby
Util::RandomWordsUtil (Tried Approach-1) # get_tables_of_random_words could not be found error is prompt from get_random_word method
module Util
module RandomWordsUtil
def self.included(base)
class << base
def get_tables_of_random_words
# Implementation here
end
private :get_tables_of_random_words
end
end
module_function
def get_random_word
# invoke get_tables_of_random_words
end
end
end
Util::RandomWordsUtil (Tried Approach-2) # 控制器提示错误,说未定义的局部变量或方法 'get_random_word'
module Util
module RandomWordsUtil
def self.included(base)
class << base
def get_random_word
# invoke get_tables_of_random_words
end
private
def get_tables_of_random_words
# Implementation here
end
end
end
end
end
谢谢,
吉格尼什
【问题讨论】:
标签: ruby-on-rails module private-methods