我正在试图找出如何解决eval()在Ruby 1.8.6中使用代码时出现的语法错误.
我希望以下Ruby代码:
#!/usr/bin/ruby
good_str = "(1+1)"
bad_str = "(1+1" # syntax error: missing closing paren
begin
puts eval(good_str)
puts eval(bad_str)
rescue => exc
puts "RESCUED!"
end
Run Code Online (Sandbox Code Playgroud)
运行时产生以下结果:
2
RESCUED!
Run Code Online (Sandbox Code Playgroud)
相反,我得到的是:
2
eval_rescue.rb:8: (eval):1: compile error (SyntaxError)
(eval):1: syntax error, unexpected $end, expecting ')'
Run Code Online (Sandbox Code Playgroud)
似乎eval方法引发的SyntaxError正在eval中的某个地方被拯救,而我没有机会自己处理它.
任何人都知道如何获得我想要的行为(即,我的'rescue'条款从'eval'中捕获错误)?
我正在使用多态关联来跟踪我的项目中的注释.所有非常直接的东西.
我遇到的问题是基于多态关联查询并从Comment模型加入到它的所有者.
所以......
我有一个评论模型
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
Run Code Online (Sandbox Code Playgroud)
和ForumTopics模式:
class ForumTopic < ActiveRecord::Base
has_many :comments, :as => :commentable
end
Run Code Online (Sandbox Code Playgroud)
我还有其他几个"可评论"的模型,现在并不重要.所有这一切都有效.
我想要做的是找到属于具有指定条件的ForumTopic的所有注释(在这种情况下,'featured'== true).
当我尝试使用finder加入模型时:
@comments = Comment.find(:all
:joins => :commentable
:conditions => ["forum_topics.featured = ? ", true]
)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
无法急切加载多态关联:可评论
使用AR"包含语法":
@comments = Comment.find(:all
:include => :forum_topics
:conditions => ["forum_topics.featured = ? ", true]
)
Run Code Online (Sandbox Code Playgroud)
收益:
未找到名为"forum_topics"的协会; 也许你拼错了吗?
如果我尝试使用表名而不是关联名(字符串而不是符号)加入:
@comments = Comment.find(:all,
:joins => "forum_topics",
:conditions => ["forum_topics.featured = ? ", true]
)
Run Code Online (Sandbox Code Playgroud)
我知道了:
Mysql …
我在我的应用程序中使用restful_authentication.我正在使用rake任务创建一组默认用户,但每次运行任务时都会因为与我的用户模型关联的观察者而发送激活电子邮件.我在创建用户时设置激活字段,因此不需要激活.
任何人都知道在运行rake任务时绕过观察者的简单方法,以便在我保存用户时不会发送电子邮件?
谢谢.
我非常格式化浮点数,但如果没有相关的浮点数,则希望它显示为整数.
即
我可以通过一些正则表达式实现这一点,但想知道是否有sprintf这样做的唯一方法?
我喜欢懒洋洋地在红宝石中这样做:
("%0.2fx" % (factor / 100.0)).gsub(/\.?0+x$/,'x')
Run Code Online (Sandbox Code Playgroud) 我想从网页中提取所有网址,我怎么能用nokogiri呢?
例:
<div class="heat"> <a href='http://example.org/site/1/'>site 1</a> <a href='http://example.org/site/2/'>site 2</a> <a href='http://example.org/site/3/'>site 3</a> </diV>
结果应该是一个列表:
l = ['http://example.org/site/1/', 'http://example.org/site/2/', 'http://example.org/site/3/' 在Windows上,Ruby的特定技术原因是什么?人们报告Linux/OSX的速度下降了3倍,并且有一些模糊的讨论关于Ruby使用Windows版本的编译器产生慢代码,但我找不到任何具体的细节.
谁知道具体细节?我对hurf durf不感兴趣,Windoze糟透了yuk yuks.
我想从字节值构建一个字符串.
我目前使用:
str = " "
str[0] = byte
Run Code Online (Sandbox Code Playgroud)
这似乎工作正常,但我觉得它很难看,并且不能很好地扩展到超过1个字符的字符串.
任何的想法?
Ruby on Rails已经成为服务器编程行业的一个新的竞争对手,以及php,asp.net,jsp,python和其他一些.但红宝石用于什么BESIDES导轨?是否将其所有成功归功于rails框架?这里有更多问题标记为ruby-on-rails而不是ruby.但是,我认为PHP不是用于服务器之外的东西,
想法?
码:
c = 0
items.each { |i|
puts i.to_s
# if c > 9 escape the each iteration early - and do not repeat
c++
}
Run Code Online (Sandbox Code Playgroud)
我想抓住前10个项目,然后离开"每个"循环.
我该如何用?替换注释行?有更好的方法吗?更多Ruby惯用的东西?