开发者

what does an exclamation mark follow with variable mean in ruby on rails?

开发者_Python百科i was reading tutorials for rails 3 with mongodb

and i see something like this

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

what does the exclamation mark mean??? Thanks.

  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


That's defined in 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


In Ruby, methods are allowed to end with question marks (method_name?) or exclamation marks (method_name!).

Semantics of them is up to programmer. There is a convention to use exclamation marks to indicate that method will modify the object it's called on, but plenty of folk use them for other purposes.

In your case, I suppose, it means something like "do it!", to make obvious at a glance that the method is going to have some "interesting" side effect.


Wow! This just completely officiated why my suspicions about Rails being a totally ridiculous framework are all substantiated! Let's let developers dictate what something means. Really?!

http://phpvsrails.blogspot.com/

That about says it all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜