naming & refactor

Extract Variable(提取变量)

def calculate(value)
  value * 0.07
end

To

SALES_TAX = 0.07

def calculate(value)
  value * SALES_TAX
end
content.gsub(/\s+$/, '')

To

TRAILING_WHITESPACE_PATTERN = /\s+$/

content.gsub(TRAILING_WHITESPACE_PATTERN, '')

Extract Method(提取方法)

def show_sample?(video)
  video.has_sample? && \
    current_user.present? && !current_user.subscriber?
end

To

def show_sample?(video)
  video.has_sample? && sampler?
end

private

def sampler?
  current_user.present? && !current_user.subscriber?
end

Convert Comment to Method(方法替代注释)

# find the user based on the email in the params
user = User.find_by(email: params[:user_email])

To

user = find_user_by_email_param

# elsewhere in file

def find_user_by_email_param
  User.find_by(email: params[:user_email])
end

Examples

# Parses a URL for a `return_to` path.
class ReturnPathFinder
  def initialize(url)
    @url = url
  end

  def return_path
    query_string['return_to']
  end

  private

  attr_reader :url

  def query_string
    Rack::Utils.parse_nested_query(parsed_url.query)
  end

  def parsed_url
    URI.parse(url)
  end
end

ReturnPathFinder.new(auth_origin).return_path

你可能感兴趣的:(naming & refactor)