【问题标题】:what does an exclamation mark follow with variable mean in ruby on rails?在 ruby​​ on rails 中,感叹号后面是什么意思?
【发布时间】:2011-09-09 18:33:48
【问题描述】:

我正在阅读使用 mongodb 的 rails 3 教程

我看到了这样的东西

  # Note this: ids are of class ObjectId.
  key :user_id,   ObjectId
  timestamps!

感叹号是什么意思??? 谢谢。

  class Story
      include MongoMapper::Document

      key :title,     String
      key :url,       String
      key :slug,      String
      key :voters,    Array
      key :votes,     Integer, :default => 0
      key :relevance, Integer, :default => 0

      # Cached values.
      key :comment_count, Integer, :default => 0
      key :username,      String

      # Note this: ids are of class ObjectId.
      key :user_id,   ObjectId
      timestamps!

      # Relationships.
      belongs_to :user

      # Validations.
      validates_presence_of :title, :url, :user_id
    end

【问题讨论】:

    标签: ruby-on-rails-3 mongodb mongomapper


    【解决方案1】:

    哇!这完全证明了为什么我对 Rails 是一个完全荒谬的框架的怀疑都得到了证实!让我们让开发人员决定某事的含义。真的吗?!

    http://phpvsrails.blogspot.com/

    这说明了一切。

    【讨论】:

    • 是的,你完全正确,因为空间内的标准、规范和共识总是一个糟糕的想法....*结束讽刺* 去其他地方巨魔。
    【解决方案2】:

    在 Ruby 中,方法可以以问号(method_name?)或感叹号(method_name!)结尾。

    它们的语义取决于程序员。习惯上使用感叹号来表示该方法将修改它所调用的对象,但很多人将它们用于其他目的。

    在你的情况下,我想,它的意思是“做它!”,一目了然地表明该方法将产生一些“有趣”的副作用。

    【讨论】:

      【解决方案3】:

      这是在 MongoMapper::Document: 中定义的:

      https://github.com/jnunemaker/mongomapper/blob/master/lib/mongo_mapper/plugins/timestamps.rb

          def timestamps!
            key :created_at, Time
            key :updated_at, Time
            class_eval { before_save :update_timestamps }
          end
      

      【讨论】:

        猜你喜欢
        • 2011-09-09
        • 2018-01-05
        • 2021-09-18
        • 2011-01-11
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多