Sha256: f9adadeb4fdb69141a6dec88926d1e2b571e64cbc4dfdaeba4fe14eab7bd4e7f

Contents?: true

Size: 2 KB

Versions: 14

Compression:

Stored size: 2 KB

Contents

class PaidUp::Plan < ActiveRecord::Base
  has_many :features_plans, class_name: 'PaidUp::FeaturesPlan'
  has_many :features, :through => :features_plans, class_name: 'PaidUp::Feature'

  validates_presence_of :description, :name

  after_initialize :load_stripe_data

  attr_accessor :stripe_data

  default_scope { order('sort_order ASC') }
  scope :subscribable, -> { where('sort_order >=  ?', 0) }
  scope :free, -> { find_by_stripe_id(PaidUp.configuration.free_plan_stripe_id) }

  def reload(*args, &blk)
    super *args, &blk
    load_stripe_data
    self
  end

  def feature_setting_by_name(feature_name)
    feature = PaidUp::Feature.find_by_name(feature_name) || raise(:feature_not_found.l)
    feature_setting(feature.id)
  end

  def feature_setting(feature_id)
    feature = PaidUp::Feature.find(feature_id) || raise(:feature_not_found.l)
    raw = features_plans.where(feature_id: feature_id)
    case feature.setting_type
      when 'boolean'
        if raw.empty?
          false
        else
          raw.first.setting != 0
        end
      when 'table_rows'
        if raw.empty?
          0
        else
          raw.first.setting
        end
      else
        raise :error_handling_feature_setting.l feature: feature
    end
  end

  def feature_unlimited?(feature_id)
    feature_setting(feature_id) == PaidUp::Unlimited.to_i
  end

  def interval
    if stripe_data.present?
      stripe_data.interval
    else
      :default_interval.l
    end
  end

  def interval_count
    if stripe_data.present?
      stripe_data.interval_count
    else
      1
    end
  end

  def amount
    if stripe_data.present?
      stripe_data.amount
    else
      0
    end
  end

  def money
    Money.new(amount, currency)
  end

  def charge
    money.amount
  end

  def currency
    if stripe_data.present?
      stripe_data.currency.upcase
    else
      :default_currency.l.upcase
    end
  end

  private

  def load_stripe_data
    if stripe_id.present?
      self.stripe_data = Stripe::Plan.retrieve stripe_id
    end
  end

end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
paid_up-0.2.4 app/models/paid_up/plan.rb
paid_up-0.2.3 app/models/paid_up/plan.rb
paid_up-0.2.2 app/models/paid_up/plan.rb
paid_up-0.2.1 app/models/paid_up/plan.rb
paid_up-0.2.0 app/models/paid_up/plan.rb
paid_up-0.1.9 app/models/paid_up/plan.rb
paid_up-0.1.8 app/models/paid_up/plan.rb
paid_up-0.1.7 app/models/paid_up/plan.rb
paid_up-0.1.6 app/models/paid_up/plan.rb
paid_up-0.1.5 app/models/paid_up/plan.rb
paid_up-0.1.4 app/models/paid_up/plan.rb
paid_up-0.1.3 app/models/paid_up/plan.rb
paid_up-0.1.1 app/models/paid_up/plan.rb
paid_up-0.1.0 app/models/paid_up/plan.rb