Module: TimeZoneScheduler::View

Defined in:
lib/time_zone_scheduler/view.rb

Defined Under Namespace

Modules: Mixin

Instance Method Summary collapse

Instance Method Details

#in_time_zonesArray<Mongoid::Criteria, ActiveRecord::Relation, TimeZoneScheduler::View::Mixin>

Defines a singleton method called in_time_zones which returns a list of views on the model partitioned by the time zones available in the specified time zone model field.

Returns views that are regular Mongoid::Criteria or ActiveRecord::Relation instances created from the current scope (and narrowed down by time zone), but are extended with the TimeZoneScheduler API.

Examples:


class User
  field :time_zone, type: String

  extend TimeZoneScheduler::View
  view_field_as_time_zone :time_zone
end

User.create(time_zone: 'Europe/Amsterdam')
time_zone_view = User.in_time_zones.first

p time_zone_view # => #<User where: { time_zone: 'Europe/Amsterdam' }>
p time_zone_view.time_zone # => 'Europe/Amsterdam'
p time_zone_view.time_zone_scheduler # => #<TimeZoneScheduler>

# See TimeZoneScheduler for documentation on these available methods.
time_zone_view.schedule_on_date(time)
time_zone_view.schedule_in_timeframe(time, timeframe)
time_zone_view.in_timeframe?(time, timeframe)

Returns:

See Also:



81
82
83
# File 'lib/time_zone_scheduler/view.rb', line 81

def in_time_zones
  raise 'Need to call view_field_as_time_zone first.'
end

#view_field_as_time_zone(time_zone_field, default_time_zone = nil) ⇒ void

This method returns an undefined value.

Defines a singleton method called in_time_zones which returns a list of views on the model partitioned by the time zones available in the specified time zone model field.

It is able to extend ActiveRecord and Mongoid models.

Parameters:

  • time_zone_field (Symbol)

    the model field that holds the time zone names.

  • default_time_zone (String) (defaults to: nil)

    the time zone to use if the value of the field can be nil.

See Also:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/time_zone_scheduler/view.rb', line 22

def view_field_as_time_zone(time_zone_field, default_time_zone = nil)
  time_zone_scopes = lambda do |scope, time_zones|
    time_zones.map do |time_zone|
      scope.where(time_zone_field => time_zone).tap do |scope|
        scope.extend Mixin
        scope.time_zone_scheduler = TimeZoneScheduler.new(time_zone || default_time_zone)
      end
    end
  end

  if respond_to?(:scoped)
    # Mongoid
    define_singleton_method :in_time_zones do
      time_zone_scopes.call(scoped, scoped.distinct(time_zone_field))
    end
  elsif respond_to?(:scope)
    # ActiveRecord (has dropped `scoped` since v4.0.2)
    define_singleton_method :in_time_zones do
      time_zone_scopes.call(scope, scope.select(time_zone_field).distinct)
    end
  else
    raise 'Unknown ORM.'
  end
end