Essentail Rails Design Pattern

Write Good Rails Code

Model 超過 2.5 頁

場景

#TODO

Extract to Module

1
2
3
4
5
class Post < ActiveRecord::Base
  include MySite::PostBase

  # ... some bussiness logic method here
end

Common Behavior

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module MySite
  module PostBase
  extend ActiveSupport::Concern
  included do
    included AASM
    include ExcerptMethods
    include ContentMethods
    include PermalinkMethods

    aasm_state :submitted, :enter => :notifiy_reviewer
    aasm_state :published

    before_save :randomize_excerpt_image_file_name

  end

  module ClassMethods
  end

  module InstanceMethods

    def is_scheduled?
      aasm_state == "published"  published_at > Time.zone.now
    end
  end
end

使用 STI / NameSpace

Single Table Inheritance

1
2
3
4
5
  class TechbangPost < Post
  end

  class AdvertisePost < Post
  end

NameSpace

1
2
3
4
5
class User::Profile < ActiveRecord::Base
end

class User::Preference < ActiveRecord::Base
end

Extract to composed class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Customer < ActiveRecord::Base
   composed_of :address, :mapping => [ %w(address_street street),
                                       %w(address_city city)]
end

class Address
  attr_reader :street
  def initialize(street)
    @street, @city = street, city
  end

  def close_to?(other_address)
    city = other_address.city
  end
end

Comments