Module: Replyr::AddressBuilder

Included in:
BounceAddress, ReplyAddress
Defined in:
lib/replyr/address_builder.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.class_from_normalized_model_name(model_name) ⇒ Object

Converts a normalized model_name back to a real model name and returns the class



17
18
19
# File 'lib/replyr/address_builder.rb', line 17

def self.class_from_normalized_model_name(model_name)
  model_name.gsub("+", "/").classify.constantize
end

.get_parsed_address(address) ⇒ Object

Split the reply/bounce email address. It has the following format: Reply: reply-comment-12-56-01ce26dc69094af9246ea7e7ce9970aff2b81cc9@reply.example.com Bounce: bounce-newsletter-12-01ce26dc69094af9246ea7e7ce9970aff2b81cc9@bounce.example.com



32
33
34
35
36
37
38
# File 'lib/replyr/address_builder.rb', line 32

def self.get_parsed_address(address)
  if match_data = Replyr.route.match(address)
    match_data
  else
    raise ArgumentError, "Malformed reply/bounce email address."
  end
end

Instance Method Details

#create_token(model, user = nil) ⇒ Object

Creates a token from the passed model (and user if passed) Uses the configured secret as a salt



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/replyr/address_builder.rb', line 43

def create_token(model, user = nil)
  user_id = user.present? ? id_from_model(user) : nil
  model_id = id_from_model(model)
  model_name = normalized_model_name(model)

  OpenSSL::HMAC.hexdigest(
    OpenSSL::Digest.new('sha1'),
    Replyr.config.secret,
    [user_id, model_name, model_id].compact.join("-")
  )
end

#ensure_valid_token!(token) ⇒ Object

Ensure a given token is valid

Raises:

  • (RuntimeError)


63
64
65
# File 'lib/replyr/address_builder.rb', line 63

def ensure_valid_token!(token)
  raise(RuntimeError, "Token invalid.") unless token_valid?(token)
end

#id_from_model(object) ⇒ Object

Returns the ID of an AR object. Uses primary key to find out the correct field



24
25
26
# File 'lib/replyr/address_builder.rb', line 24

def id_from_model(object)
  object.send(object.class.primary_key)
end

#normalized_model_name(model) ⇒ Object

Model name may be namespaced (e.g. MyApp::Comment) For the reply email address the model name will be converted to “my_app/comment”. Then the slash “/” will be replaced with a plus sign “+”, because slashes should not be used email addresses.



10
11
12
# File 'lib/replyr/address_builder.rb', line 10

def normalized_model_name(model)
  model.class.name.tableize.singularize.gsub("/", "+")
end

#token_valid?(token) ⇒ Boolean

Check if a given token is valid

Returns:

  • (Boolean)


57
58
59
# File 'lib/replyr/address_builder.rb', line 57

def token_valid?(token)
  token == self.token
end