新手问题 想问一下,Ruby 当中是如何解决 Import 这个问题的?

cqcn1991 · 2016年02月18日 · 最后由 cqcn1991 回复于 2016年02月18日 · 1999 次阅读

现在写 Python 的时候,碰到了这样一个问题,想看看 Ruby 当中是怎么解决的

我把我的 helper methods 做了这样的组织 [![enter image description here][1]][1]

在代码中,要使用这些代码的话,必须要这样子 Import:

from helpers.utility_helper import *
from helpers.app_helper import *
from helpers.gmm_helper import *
from helpers.plot_helper import *

这样子,才可以直接使用每个 submodule 里面的 helper, 比如,用my_helper()而不是 helpers.utility_helper.my_helper().

但是这样每个 submodule import 依然很麻烦,Python 似乎连 import * from helpers/* 这种类型的 import 都不支持

我在用 Rails 的时候,似乎从来没考虑过某个 helper 来自某个 submodule, view 下面直接用就行了。不知道 Ruby 有这种限制吗?

[1]: http://i.stack.imgur.com/Tz9jc.png

_init_.py 里设置_all_变量。

#1 楼 @galeno 那个只是 import 了所有的 submodule, 使用的话还是要 sub module.my_method

ruby 不需要这么重复死板的代码

Rails 里面能直接使用 helper 方法是因为约定大于配置,Rails 源码中已经自动加载文件并 include 了相关模块。

Ruby 里用 Kernel#requireKernel#require_relative 显式加载执行其它文件中的代码,也可以使用 Kernel#loadModule#autoload

其实这反映了 Python 和 Ruby 的两种不同理念,Python 强调 explicit is better than implicitsubmodule.my_method 能清晰地反映出 my_method 是在哪个文件中定义的;而 Ruby 更强调简洁,更含蓄一些,直接使用 my_method 的缺点是你不能一眼看出该方法定义在哪里,需要用 method(:my_method).source_location 查看。各有利弊!

问个别的问题,rails 的 restful 风格如果需要传 2 个参数才能确定一个资料,要怎么设置 router 和 action? 比如需要一个 id 和一个 flag,是用:member 么?但这样 url 不是会很长? 如果需要一个 year、一个 month、一个 id,资料表中只有 datetime 形式的数据,又该如何?

#4 楼 @fighterleslie 我是因为用 ide 可以直接跳转,就觉得能省就省了…尤其是小规模的代码

需要 登录 后方可回复, 如果你还没有账号请 注册新账号