Sha256: 6621af5a6f86c5ed8ae78fa075770990886ad58e15ee37357f3233939a17b009

Contents?: true

Size: 1.13 KB

Versions: 1

Compression:

Stored size: 1.13 KB

Contents

require 'phrase/api'

class Phrase::Delegate
  attr_accessor :key, :api_client
  
  def initialize(key)
    @key = key
  end
  
  def to_s
    "#{decorated_key_name}"
  end
  
  def method_missing(*args, &block)
    if @key.respond_to?(args.first)
      to_s.send(*args)
    else
      data = translation_or_subkeys
      if data.is_a?(String)
        to_s
      elsif data.respond_to?(args.first)
        data.send(*args, &block)
      else
        log "You are trying to execute the method ##{args.first} on a translation key which is not supported. Please make sure you treat your translations as strings only."
        nil
      end
    end
  end
  
private
  def decorated_key_name
    "#{Phrase.prefix}phrase_#{@key}#{Phrase.suffix}"
  end
  
  def translation_or_subkeys
    begin
      api_client.translate(@key)
    rescue Exception => e
      log "Server Error: #{e.message}"
    end
  end
  
  def api_client
    @api_client ||= Phrase::Api::Client.new(Phrase.auth_token)
  end
  
  def log(message)
    message = "phrase: #{message}"
    if defined?(Rails)
      Rails.logger.warn(message)
    else
      $stderr.puts message
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
phrase-0.2.0.beta.2 lib/phrase/delegate.rb