Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rails構成とオブジェクト指向/ rails-structure-and-object-oriented

@amyroi
June 08, 2018
1.3k

Rails構成とオブジェクト指向/ rails-structure-and-object-oriented

@amyroi

June 08, 2018
Tweet

Transcript

  1. コード配置例 # 例 app/ ├ lib/ # もしくは lib/ 配下、autoload

    │ └ aiml/ # プロダクトコードに影響しないコンポーネン │ └ aws/ # プロダクトコードに影響しないコンポーネント │ └ nlu/ # gem 化想定 │ ├ models/ │ └ concerns/ # ActiveSupport::Concern │ └ user.rb # ActiveRelation 継承 │ └ validators/ # 独自validation クラス ├ behaviors/ │ └ user_search_form.rb # Form オブジェクト │ # | Service クラス │ # | Decorator クラス │ └ nlu_manage/ # プロジェクト内で行うNLU への │ # アクセス関するクラスをまとめるnamespace │ └ project.rb # 振る舞いのクラス │ └ bot.rb # 振る舞いのクラス 2
  2. 委譲 class A def initialize(object) end def save object.save end

    end class B # object を汚染しない end class C end a = A.new(B.new) a.save a = A.new(C.new) a.save 6
  3. Formオブジェクト class UserSearchForm include ActiveModel::Model def self.search(search_params) end end class

    User # object を汚染しない end # Usage UserSearchForm.search(params) 12
  4. Decoratorパターンで役割を分離した例 class UserCreateDecorator include ActiveModel::Model attr_accessor :user define_model_callback :save before_save

    :set_project def save User.transaction do run_callbacks(:save) do @user.save end end end def set_project @user.project = Project.create end end user = UserCreateDecorator.new(User.new) user.save 15