Código amigable: Limpieza de Chakras con RubyCritic
Ingeniero de La UD
RubyCritic: Code Smells, Flay y Flog
¡Ahora en Acción!
¡GRACIAS!
Un módulo es una colección de métodos y constantes.
Namespaces
Mixins
No state dependent
module Trig
PI = 3.141592654
def Trig.sin(x)
# ..
end
def Trig.cos(x)
# ..
end
end
module Action
VERY_BAD = 0
BAD = 1
def Action.sin(badness)
# ...
end
end
y = Trig.sin(Trig::PI/4)
wrongdoing = Action.sin(Action::VERY_BAD)
Herencia Múltiple ?
Evitar la Duplicación de Lógica
module Debug
def whoAmI?
"#{self.type.name} (\##{self.id}): #{self.to_s}"
end
end
class Phonograph
include Debug
# ...
end
class EightTrack
include Debug
# ...
end
ph = Phonograph.new("West End Blues")
et = EightTrack.new("Surrealistic Pillow")
ph.whoAmI? → "Phonograph (#537766170): West End Blues"
et.whoAmI? → "EightTrack (#537765860): Surrealistic Pillow"
class API
def fetch(id)
HTTP.get('http://matt.aimonetti.net/article/:id', :id => id)
end
end
resource = API.new.fetch(42)
module API
def self.fetch(id)
HTTP.get('http://matt.aimonetti.net/article/:id', :id => id)
end
end
resource = API.fetch(4)
class Post < ActiveRecord::Base
validates :title, :content, presence: true
has_many :votes
has_many :comments
def vote!
votes.create
end
end
class Comment < ActiveRecord::Base
validates :content, presence: :true
belongs_to :post
end
class Vote < ActiveRecord::Base
belongs_to :post
end
Hasta ahora todo va bien
class Post < ActiveRecord::Base
validates :title, :content, presence: true
has_many :votes, as: :votable
has_many :comments
def vote!
votes.create
end
end
class Comment < ActiveRecord::Base
validates :content, presence: :true
has_many :votes, as: :votable
belongs_to :post
def vote!
votes.create
end
end
class Vote < ActiveRecord::Base
belongs_to :votable, polymorphic: true
end
class Vote < ActiveRecord::Base
enum type: [:upvote, :downvote]
validates :type, presence: true
belongs_to :votable, polymorphic: true
end
module Votable
extend ActiveModel::Concern
included do
has_many :votes, as: :votable
end
def upvote!
votes.create(type: :upvote)
end
def downvote!
votes.create(type: :downvote)
end
end
class Post < ActiveRecord::Base
include Votable
validates :title, :content, presence: true
has_many :comments
end
class Comment < ActiveRecord::Base
include Votable
validates :content, presence: :true
belongs_to :post
end
¿Preguntas?
Gracias!