Class: When::TM::TemporalPosition

Inherits:
Object
  • Object
show all
Extended by:
When, Coordinates
Includes:
Comparable, When, Coordinates, Parts::Resource, IndeterminateValue, Conversion
Defined in:
lib/when_exe/tmposition.rb,
lib/when_exe/inspect.rb

Overview

「時間位置」の基底クラス

see gml schema

Direct Known Subclasses

CalDate, ClockTime, Coordinate, OrdinalPosition

Defined Under Namespace

Modules: Conversion

Constant Summary collapse

HashProperty =
Position::HashProperty
AMPM =
['AM', 'PM'].map {|half| When::Parts::Resource._instance('_m:CalendarFormats::' + half)}
Format =
{
  'a' => ['%s',   'a'], 'A' => ['%s',   'A'], 'b' => ['%s',   'b'], 'B' => ['%s',   'B'],
  'c' => When::Parts::Resource._instance('_m:CalendarFormats::DateTime'),
  'C' => ['%02d', 'C'], 'd' => ['%02d', 'd'], 'D' => '%m/%d/%y',    'e' => ['%2d',  'd'],
  'E' => ['%s',   'E'], 'F' => ['%s',   'F'], 'G' => ['%d',   'G'], 'g' => ['%02d', 'g'],
  'h' => '%b',          'H' => ['%02d', 'H'], 'I' => ['%02d', 'I'], 'j' => ['%03d', 'j'],
  'k' => ['%2d',  'H'], 'l' => ['%2d',  'I'], 'm' => ['%02d', 'm'], 'M' => ['%02d', 'M'],
  'n' => '\n',          'p' => ['%s',   'p'], 'P' => ['%s',   'P'], 'r' => '%I:%M:%S %p',
  'R' => '%H:%M',       's' => ['%d',   's'], 'S' => ['%02d', 'S'], 't' => '\t',
  'T' => '%H:%M:%S',    'u' => ['%d',   'u'], 'U' => ['%02d', 'U'], 'V' => ['%02d', 'V'],
  'w' => ['%d',   'w'], 'W' => ['%02d', 'W'],
  'x' => When::Parts::Resource._instance('_m:CalendarFormats::Date'),
  'X' => When::Parts::Resource._instance('_m:CalendarFormats::Time'),
  'y' => ['%02d', 'y'], 'Y' => ['%4d',  'Y'], 'z' => ['%s',   'z'], 'Z' => ['%s',   'Z'],
  '+' => '%a %b %d %T %z %Y'
}

Constants included from Coordinates

Coordinates::Bahai, Coordinates::CommonResidue, Coordinates::DefaultDateIndex, Coordinates::DefaultTimeIndex, Coordinates::IndianCities, Coordinates::Javanese, Coordinates::MATCH, Coordinates::Mayan, Coordinates::PERIOD, Coordinates::PERIOD_NAME, Coordinates::PRECISION, Coordinates::PRECISION_NAME, Coordinates::VALUE, Coordinates::Yi

Constants included from When

CENTURY, DAY, DECADE, DurationP1D, DurationP1M, DurationP1W, DurationP1Y, EUCJP, HOUR, MINUTE, MONTH, SECOND, STRING, SYSTEM, SourceURI, When::TimeValue, UTF8, VERSION, W31J, WEEK, YEAR

Constants included from Parts::Resource

Parts::Resource::LabelProperty, Parts::Resource::Prefix, Parts::Resource::PrefixIndex, Parts::Resource::PrefixKeys, Parts::Resource::PrefixValues

Constants included from IndeterminateValue

IndeterminateValue::After, IndeterminateValue::Before, IndeterminateValue::I, IndeterminateValue::Max, IndeterminateValue::Min, IndeterminateValue::Now, IndeterminateValue::S, IndeterminateValue::Unknown

Class Attribute Summary collapse

Instance Attribute Summary collapse

Attributes included from Parts::Resource

#_pool, #child, #keys, #locale, #namespace

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Coordinates

to_deg, to_dms

Methods included from When

Calendar, CalendarEra, CalendarNote, Clock, Duration, M17n, MonthName, Pair, Residue, Resource, TemporalPosition, _free_conv, _parse, at, client, config, era, free_conv, m17n, now, server, today, utc, when?

Methods included from Conversion

#julian_date, #tm_position

Methods included from Parts::Resource

_extract_prefix, _parse, _path_with_prefix, #each, #enum_for, #hierarchy, #included?, #iri, #leaf?, #m17n, #map, #parent, #registered?

Methods included from Parts::Resource::Pool

#[]=, #_pool, #_setup_, #pool_keys

Methods included from Parts::Resource::Synchronize

#synchronize

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (private)

Note:

When::TM::TemporalPosition で定義されていないメソッドは 処理を @frame (type: When::TM::Calendar or When::TM::Clock) に委譲する

その他のメソッド



965
966
967
# File 'lib/when_exe/tmposition.rb', line 965

def method_missing(name, *args, &block)
  @frame.send(name.to_sym, self, *args, &block)
end

Class Attribute Details

.formatObject

strftime で用いる書式のハッシュ



165
166
167
# File 'lib/when_exe/inspect.rb', line 165

def format
  @format
end

Instance Attribute Details

#eventsArray<When::Parts::Enumerator>

この時間位置と関連付けられたイベント - additional attribute



221
222
223
# File 'lib/when_exe/tmposition.rb', line 221

def events
  @events
end

#frameWhen::TM::ReferenceSystem Also known as: clock

この時間位置と関連付けられた時間参照系 (relation - Reference)

The time reference system associated with the temporal position being described



214
215
216
# File 'lib/when_exe/tmposition.rb', line 214

def frame
  @frame
end

#indeterminated_positionWhen::TM::IndeterminateValue (readonly) Also known as: indeterminatedPosition

この時間位置の意味づけ



205
206
207
# File 'lib/when_exe/tmposition.rb', line 205

def indeterminated_position
  @indeterminated_position
end

#locationWhen::Coordinates::Spatial

その他の属性 - additional attribute



252
253
254
# File 'lib/when_exe/tmposition.rb', line 252

def location
  @location
end

#optionsHash (readonly)

その他の属性 - additional attribute

Returns:

  • (Hash)

    { String=>Object }



234
235
236
# File 'lib/when_exe/tmposition.rb', line 234

def options
  @options
end

#precisionNumeric

この時間位置の分解能 - additional attribute

Returns:



228
229
230
# File 'lib/when_exe/tmposition.rb', line 228

def precision
  @precision
end

#queryHash

その他の属性 - additional attribute

Returns:

  • (Hash)

    { String=>When::BasicTypes::M17n }



246
247
248
# File 'lib/when_exe/tmposition.rb', line 246

def query
  @query
end

#transHash

その他の属性 - additional attribute

Returns:

  • (Hash)

    { String=>Object }



240
241
242
# File 'lib/when_exe/tmposition.rb', line 240

def trans
  @trans
end

Class Method Details

._instance(specification, options = {}) ⇒ When::TM::TemporalPosition, ...

Temporal Objetct の生成

Parameters:

  • specification (String)

    When.exe Standard Representation

  • options (Hash) (defaults to: {})

    下記の通り

Options Hash (options):

  • :frame (When::TM::ReferenceSystem)

    暦法の指定

  • :clock (When::TM::Clock)

    時法の指定

  • :tz (When::Parts::Timezone)

    時法の指定(時間帯を指定する場合 :clock の替わりに用いることができる)

  • :abbr (Array<Numeric>)

    ISO8601上位省略形式のためのデフォルト日付(省略時 指定なし)

  • :wkst (String)

    ISO8601週日形式のための暦週開始曜日(省略時 ‘MO’)

  • :precision (Integer)

    生成するオブジェクトの分解能

  • :time_standard (When::TimeStandard::TimeStandard)

    時刻系の指定(省略時 When::TimeStandard::UnversalTime)

  • :location (When::Ephemeris::Spatial)

    観測地の指定(省略時 指定なし)

  • :era_name (String)

    暦年代

  • :trans (Hash)

    暦年代の上下限

    • :count => 条件に合致する暦年代のうち何番目を採用するか

    • :lower => 暦年代適用の下限

      true            - epoch_of_use の始め(省略時)
      :reference_date - 参照事象の日付
      
    • :upper => 暦年代適用の上限

      true            - epoch_of_use の終わり(省略時)
      :reference_date - 参照事象の日付
      
  • :query (Hash)

    暦年代の絞込み条件

    • :area => area による暦年代絞込み

    • :period => period による暦年代絞込み

    • :name => name による暦年代絞込み(epoch の attribute使用可)

Returns:



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/when_exe/tmposition.rb', line 289

def _instance(specification, options={})

  # Suffix - Frame specification
  rfc5545form, frame, *rest = specification.split(/\^{1,2}/)
  return rest.inject(_instance(rfc5545form + '^' + frame, options)) {|p,c| When.Resource(c, '_c:').jul_trans(p)} if rest.size > 0

  options[:frame] = When.Resource(frame, '_c:') if (frame)

  # Prefix - RFC 5545 Options
  if (rfc5545form =~ /^([^:]+[^-:\d]):([^:].+)$/)
    rfc5545option, iso8601form = $~[1..2]
    rfc5545option.split(/;/).each do |eq|
      key, value = eq.split(/=/, 2)
      case key
      when 'VALUE' ; options[:precision] = value
      when 'TZID'  ; options[:clock] = 
        case When::V::Timezone[value]
        when Array ; When::V::Timezone[value][-1]
        when nil   ; When::Parts::Timezone.new(value)
        else       ; When::V::Timezone[value]
        end
      else         ; options[key]    = value
      end
    end
  else
    iso8601form = rfc5545form
  end
  options = options.dup

  # IndeterminateValue
  if (iso8601form.sub!(/\/After$|^Before\/|^Now$|^Unknown$|^[-+]Infinity$/i, ''))
    options[:indeterminated_position] = When::TimeValue::S[$&.sub(/\//,'')]
    case options[:indeterminated_position]
    when When::TimeValue::Now,
         When::TimeValue::Unknown,
         When::TimeValue::Max,
         When::TimeValue::Min
      return self.new(self._options(options))
    end
  end

  # each specification
  splitted = iso8601form.split(/\//)
  if (splitted[0] =~ /^R(\d+)?$/)
    repeat = $1 ? $1.to_i : true
    splitted.shift
  end
  case splitted.length
  when 1
  when 2
    if (splitted[0] !~ /^[-+]?P/ && splitted[1] =~ /^\d/ && splitted[1].length < splitted[0].length)
      splitted[1] = splitted[0][0..(splitted[0].length-splitted[1].length-1)] + splitted[1]
    end
  else
    raise ArgumentError, "Irregal ISO8601 Format: #{iso8601form}"
  end
  options = self._options(options)
  element = splitted.map { |v| _date_time_or_duration(v, options.dup) }

  # total result
  case repeat
  when nil
    case element[1]
    when nil
      return element[0]
    when Duration
      case element[0]
      when Duration ; raise TypeError, "Duplicate Duration: #{element[0]} and #{element[1]}"
      when self     ; return When::Parts::GeometricComplex.new(*element)
      else          ; return When::Parts::GeometricComplex.new(element[0].first, element[1])
      end
    when self
      case element[0]
      when Duration ; return When::Parts::GeometricComplex.new([[element[1]-element[0],false], [element[1],true ]])
      when self     ; return When::Parts::GeometricComplex.new(element[0]..element[1])
      else          ; return When::Parts::GeometricComplex.new(element[0].first..element[1])
      end
    else
      case element[0]
      when Duration ; return When::Parts::GeometricComplex.new([[element[1].first-element[0],false],
                                                                [element[1].last-element[0]-1,true ]])
      when self     ; return When::Parts::GeometricComplex.new(element[0]...element[1].last)
      else          ; return When::Parts::GeometricComplex.new(element[0].first...element[1].last)
      end
    end
  when 0            ; return []
  when Integer      ; return [element[0]] * repeat unless element[1]
  end

  case element[1]
  when Duration
    case element[0]
    when Duration   ; raise TypeError, "Duplicate Duration: #{element[0]} and #{element[1]}"
    else            ; duration = element[1]
    end
  when self
    case element[0]
    when Duration   ; duration = -element[0]
    when self       ; duration =  element[1] - element[0]
    else            ; duration =  element[1] - element[0].first
    end
  else
    case element[0]
    when Duration   ; duration = -element[0]
    when self       ; duration =  element[1].first - element[0]
    else            ; duration =  element[1].first - element[0].first
    end
  end
  base = element[0].kind_of?(Duration) ? element[1] : element[0]

  if repeat.kind_of?(Integer)
    result = case base
             when self  ; (1..repeat-1).inject([base]) {|a,i| a << (a[-1] + duration) }
             else       ; (1..repeat-1).inject([base]) {|a,i| a << When::Parts::GeometricComplex.new(
                                                                    a[-1].first+duration...a[-1].last+duration)}
             end
    result.reverse! if duration.sign < 0
    return result

  else
    duration = -duration if duration.sign < 0
    return case base
           when self    ; When::V::Event.new({'rrule'=>{'FREQ'=>duration}, 'dtstart'=>base})
           else         ; When::V::Event.new({'rrule'=>{'FREQ'=>duration}, 'dtstart'=>base.first,
                                                                           'dtend'  =>base.last})
           end
  end
end

._options(options) ⇒ Object

option の正規化



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/when_exe/tmposition.rb', line 420

def _options(options)
  query = options.dup
  main  = {}
  clock = Clock.get_clock_option(query)
  main[:clock] = clock if clock
  [:indeterminated_position, :frame, :events, :precision,
   :era_name, :era, :abbr, :wkst, :time_standard, :location].each do |key|
    main[key] = query.delete(key) if (query.key?(key))
  end
  trans = query.delete(:trans) || {}
  [:lower, :upper, :count].each do |key|
    trans[key] = query.delete(key) if (query.key?(key))
  end
  query = query.merge(query.delete(:query)) if (query.key?(:query))
  main[:query] = query if (query.size > 0)
  main[:trans] = trans if (trans.size > 0)
  return main
end

._setup_(format = nil) ⇒ void

Note:

format の指定がない場合、format は Format(モジュール定数)と解釈する

This method returns an undefined value.

When::TM::TemporalPosition Class のグローバルな設定を行う

Parameters:

  • format (Hash) (defaults to: nil)

    strftime で用いる記号の定義



175
176
177
# File 'lib/when_exe/inspect.rb', line 175

def _setup_(format=nil)
  @format = format ? Format.merge(format) : Format
end

Instance Method Details

#+(other) ⇒ When::TM::TemporalPosition

加算

Parameters:

Returns:



653
654
655
656
657
658
659
660
661
662
663
# File 'lib/when_exe/tmposition.rb', line 653

def +(other)
  case other
  when Integer        ; self + PeriodDuration.new(other, When::DAY)
  when Numeric        ; self + IntervalLength.new(other, 'day')
  when PeriodDuration ; _plus(other)
  when Duration       ; @frame.jul_trans(JulianDate.dynamical_time(dynamical_time + other.duration), self._attr)
  else                ; raise TypeError, "The right operand should be Numeric or Duration"
  end
rescue RangeError
  (@frame ^ self) + other
end

#+@Float

ユリウス日時(実数)

Returns:

  • (Float)

    dynamical time での経過日数を, ユリウス日と1970-01-01T00:00:00TTで時計あわせしたもの



585
586
587
# File 'lib/when_exe/tmposition.rb', line 585

def +@
  JulianDate._t_to_d(dynamical_time)
end

#-(other) ⇒ When::TM::TemporalPosition, When::TM::Duration

減算

Parameters:

Returns:



672
673
674
675
676
677
678
679
680
681
682
683
684
685
# File 'lib/when_exe/tmposition.rb', line 672

def -(other)
  case other
  when TimeValue      ; self.rate_of_clock == other.rate_of_clock && [@precision, other.precision].min <= When::DAY ?
                          PeriodDuration.new(self.to_i - other.to_i, When::DAY) :
                          IntervalLength.new((self.dynamical_time - other.dynamical_time) / Duration::SECOND, 'second')
  when Integer        ; self - PeriodDuration.new(other, When::DAY)
  when Numeric        ; self - IntervalLength.new(other, 'day')
  when PeriodDuration ; _plus(-other)
  when Duration       ; @frame.jul_trans(JulianDate.dynamical_time(dynamical_time - other.duration), self._attr)
  else                ; raise TypeError, "The right operand should be Numeric, Duration or TemporalPosition"
  end
rescue RangeError
  (@frame ^ self) - other
end

#<=>(other) ⇒ Integer

大小比較

Returns:

  • (Integer)

    (-1, 0, 1)

    分解能の低い方にあわせて比較を行う

    Ex. when?('2011-03') <=> when?('2011-03-10') -> 0
    


775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
# File 'lib/when_exe/tmposition.rb', line 775

def <=>(other)
  other  = other.first if other.kind_of?(When::Parts::GeometricComplex)
  [self.indeterminated_position, other.indeterminated_position].each do |position|
    prec = SYSTEM if [TimeValue::Min, TimeValue::Max].include?(position)
  end
  prec   = [self.precision, other.precision].min unless prec
  case prec
  when DAY    ; return self.to_i <=> other.to_i
  when SYSTEM ; src, dst = self, other
  else
    if prec < DAY && respond_to?(:most_significant_coordinate) &&
               other.respond_to?(:most_significant_coordinate) && @frame.equal?(other.frame)
      result = most_significant_coordinate <=> other.most_significant_coordinate
      return result unless result == 0 && @cal_date.length + prec > 1
      (@cal_date.length + prec - 2).times do |i|
        result = @cal_date[i+1] <=> other.cal_date[i+1]
        return result unless result == 0
      end
      return @cal_date[prec - 1] <=> other.cal_date[prec - 1]
    end
    src, dst =
      [(prec >= self.precision ) ? self  : self.floor(prec),
       (prec >= other.precision) ? other : other.floor(prec)]
  end
  return src.to_i <=> dst.to_i if prec <= DAY
  return src.universal_time <=> dst.universal_time if src.time_standard.equal?(dst.time_standard)
  return src.dynamical_time <=> dst.dynamical_time
end

#[](index) ⇒ Numeric

要素の参照

Parameters:

  • index (Integer, String)

    参照する要素の指定

Returns:



642
643
644
645
# File 'lib/when_exe/tmposition.rb', line 642

def [](index)
  return value(index) if index.kind_of?(String) || !index.respond_to?(:inject)
  index.inject([]) {|list, i| list << value(i) }
end

#^(other, leaf = true, &block) ⇒ Array of (element^self) for all When::Parts::Resource registered elements, ...

条件を満たすオブジェクトの抽出

Parameters:

Returns:

  • (Array of (element^self) for all When::Parts::Resource registered elements)

    (If other is Module)

  • (Array of (self^element) for elemnt of other which belong to the specified module or class)

    (If other is [Array])

  • (Enumerator which generates temporal position sequence begins from self with the specified duration)

    (If other is [When::TM::Duration])

  • (Array of temporal position using the specified calendar as a frame)

    (If other is [When::TM::Calendar])

  • (Array of temporal position using the specified calendar era as a calendarEraName)

    (If other is [When::TM::CalendarEra])



865
866
867
# File 'lib/when_exe/tmposition.rb', line 865

def ^(other, leaf=true, &block)
  scan(other, leaf, &block)
end

#_attrObject

属性の Hash



883
884
885
886
887
888
889
# File 'lib/when_exe/tmposition.rb', line 883

def _attr
  attributes = {}
  ['frame', 'events', 'precision', 'options', 'trans', 'query', 'time_standard'].each do |key|
    attributes[key.to_sym] = instance_variable_get("@#{key}")
  end
  return attributes
end

#_notes(options = {}) ⇒ Array<Array<Hash{:note=>note, :value=>value}>>

Note:

When::TM::TemporalPosition の場合、events に暦注名の入ったその暦注に該当する日付である。 (例) Christian クラス で easter を計算した場合、当該年の復活祭の日付オブジェクトが返る。 暦注サブクラスの場合、要素が増えたり、:note の暦注要素の型が変わったりすることがある。

時間位置オブジェクトの暦注を取得

Parameters:

  • options (String) (defaults to: {})

    { :notes => String } という Hash の指定と等価

  • options (Integer) (defaults to: {})

    { :indices => Integer } という Hash の指定と等価

  • options (Hash) (defaults to: {})

    下記のとおり

Options Hash (options):

Returns:

  • (Array<Array<Hash{:note=>note, :value=>value}>>)
    note [String, When::BasicTypes::M17n, When::Coordinates::Residue

    暦注名 ]

    value [String, When::BasicTypes::M17n, When::Coordinates::Residue, When::TM::TemporalPosition

    暦注の値 ]



462
463
464
# File 'lib/when_exe/inspect.rb', line 462

def _notes(options={})
  _calendar_note(options).notes(self, options)
end

#_to_hash(options = {}) ⇒ Hash

時間位置オブジェクトの内容を Hash 化

Parameters:

  • options (String) (defaults to: {})

    { :notes => String } という Hash の指定と等価

  • options (Integer) (defaults to: {})

    { :indices => Integer } という Hash の指定と等価

  • options (Hash) (defaults to: {})

    下記のとおり

Options Hash (options):

Returns:

  • (Hash)
    • :sdn 日の通し番号 - ユリウス通日(Integer)

    • :calendar calendar_name の結果 - Array<暦法または暦年代(, 付属情報..)>

    • :notes Hash (の Array (の Array)) - _notes(options)

    clock が定義されている場合、さらに下記も出力する

    • :clock 時計(When::TM::Clock, When::V::Timezone, When::Parts::Timezone)

    • :clk_time to_clock_time の結果 - ( 日, 時, 分, 秒 )

    • :dynamical dynamical_time / 秒

    • :universal universal_time / 秒



530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/when_exe/inspect.rb', line 530

def _to_hash(options={})
  hash = super.update({
    :sdn      => to_i,
    :calendar => calendar_name,
    :notes    => _notes(options)
  })

  hash.update({
    :clock     => clock,
    :clk_time  => to_clock_time,
    :dynamical => dynamical_time * clock.second,
    :universal => universal_time * clock.second
  }) if clock
  hash
end

#_to_sObject



557
# File 'lib/when_exe/inspect.rb', line 557

alias :_to_s :to_s

#calendar_nameArray<Class>

暦法名

Returns:

  • (Array<Class>)

    Class 暦法のクラスオブジェクト



185
186
187
# File 'lib/when_exe/inspect.rb', line 185

def calendar_name
  [self.class]
end

#clock_nameArray<String>

時法名

Returns:



194
195
196
# File 'lib/when_exe/inspect.rb', line 194

def clock_name
  [When::Parts::Resource._path_with_prefix(clock)]
end

#copy(options = {}) ⇒ When::TM::TemporalPosition

属性を変更したコピーを作る

Parameters:

  • options (Hash) (defaults to: {})

    { 属性=>属性値 }

Returns:



875
876
877
878
879
# File 'lib/when_exe/tmposition.rb', line 875

def copy(options={})
  position = self.dup
  position._copy(options)
  position
end

#dynamical_timeNumeric

外部時間

Returns:

  • (Numeric)

    1970-01-01T00:00:00TT からの terrestrial time の経過時間 / 128秒



533
534
535
536
537
538
539
540
541
# File 'lib/when_exe/tmposition.rb', line 533

def dynamical_time
  return @dynamical_time if @dynamical_time && @indeterminated_position != Now
  @dynamical_time = 
    case @indeterminated_position
    when Max ; +Float::MAX/4
    when Min ; -Float::MAX/4
    else     ; time_standard.to_dynamical_time(universal_time)
    end
end

#floor(digit = DAY, precision = digit) ⇒ When::TM::TemporalPosition

下位桁の切り捨て

Parameters:

  • digit (Integer) (defaults to: DAY)

    これより下の桁を切り捨てる(省略すると When::DAY)

  • precision (Integer) (defaults to: digit)

    切り捨て結果の分解能

Returns:



742
743
744
# File 'lib/when_exe/tmposition.rb', line 742

def floor(digit=DAY, precision=digit)
  self
end

#has_next?Boolean

前後の日時を取得可能か?

Returns:

  • (Boolean)
    true - 可能
    false - 不可


730
731
732
# File 'lib/when_exe/tmposition.rb', line 730

def has_next?
  When::Coordinates::PERIOD_NAME[@precision] != nil
end

#has_time?Boolean

分解能が時刻を持つか

Returns:

  • (Boolean)


750
751
752
# File 'lib/when_exe/tmposition.rb', line 750

def has_time?
  (@precision > 0)
end

#include?(date) ⇒ Boolean

指定の日時を含むか?

Parameters:

Returns:

  • (Boolean)
    true - 含む
    false - 含まない


762
763
764
765
# File 'lib/when_exe/tmposition.rb', line 762

def include?(date)
  return false if self.precision > date.precision
  return self == date
end

#is?(options = nil) ⇒ Boolean

指定の日時が指定イベントに該当するか?

Parameters:

  • options (String) (defaults to: nil)

    { :notes => String } または { :notes => String } または { :value => String } という Hash の指定と等価 (指定の event が存在する場合は前者、指定の notes が存在する場合は中央、しない場合は後者)

  • options (Integer) (defaults to: nil)

    { :indices => Integer } という Hash の指定と等価

  • options (Hash) (defaults to: nil)

    下記のとおり

Options Hash (options):

Returns:

  • (Boolean)
    true - 該当する
    false - 該当しない


498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/when_exe/inspect.rb', line 498

def is?(options=nil)
  calendar_note = _calendar_note(options)
  event = 
    case options
    when String ; options
    when Hash   ; options.delete(:event)
    else        ; calendar_note.event
    end
  event.to_s =~ /^([^\d]+)/ && calendar_note.respond_to?($1.downcase) ?
    calendar_note.include?(self, event) :
    calendar_note.note?(self,  options)
end

#month_included(ord, wkst, opt, block) ⇒ Range, ...

Note:

引数 ord, wkst, opt はそのクラスで位置づけを判断するため、引数の順序は任意(省略も可)

含まれる月

Parameters:

  • ord (Numeric, Range)

    月の番号(default: 今月) 今月を 0 とする月番号(Integer) または月番号の範囲(Range)

    -1 - 先月
     0 - 今月
    +1 - 来月
    
  • wkst (String)

    週の開始曜日(defaultはなし)

  • wkst (When::CalendarTypes::CalendarNote)

    暦注オブジェクト

  • wkst (Array<When::CalendarTypes::CalendarNote, String>)

    暦注オブジェクトとそのイベントメソッド名 (暦注オブジェクトは、そのIRI文字列を指定しても良い)

  • opt (Hash)

    下記の通り

  • block (Block)

Options Hash (opt):

  • :Range (Range)

    上位繰り返し範囲(ユリウス通日…ユリウス通日)

Returns:

  • (Range)

    含まれる月を範囲として表現する Range (block 指定なし)

  • (Array)

    含まれる月の各日をブロックに渡した結果の Array (block 指定あり, wkst なし)

  • (Array<Array>)

    含まれる月の各日をブロックに渡した結果の 七曜表(block 指定あり, wkst あり)



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/when_exe/inspect.rb', line 293

def month_included(*args, &block)
  first, length, wkst, opt = _range(args)
  if wkst
    (first...(first+length)).map {|i|
      begun = self.floor(MONTH,DAY) + When::TM::PeriodDuration.new([0,i,0])
      ended = begun                 + DurationP1M
      ended = ended.prev until begun.cal_date[MONTH-1] == ended.cal_date[MONTH-1]
      dates = [begun]
      loop do
        current = dates[-1].week_included(wkst)
        if ((current.first.to_i)...(current.last.to_i)).include?(ended.to_i)
          dates[-1] = ended
          break (dates.map {|date| date.week_included(wkst, {:Range=>begun.to_i..ended.to_i}, &block)}).
                unshift(yield(begun, MONTH)).compact
        elsif wkst.kind_of?(When::Coordinates::Residue)
          dates << dates[-1] + wkst.duration
        else
          it = wkst.enum_for(dates[-1], :forward)
          begin
            date = it.next
          end while date.to_i == dates[-1].to_i
          dates << date
        end
      end
    }
  else
    begun = self.floor(MONTH,DAY) + When::TM::PeriodDuration.new([0, first,  0])
    ended = begun                 + When::TM::PeriodDuration.new([0, length, 0])
    if block_given?
      (begun...ended).map do |date|
        yield(date)
      end
    else
      begun...ended
    end
  end
end

#note?(options = {}) ⇒ Boolean

暦注の一致 or 不一致

Parameters:

  • options (String) (defaults to: {})

    { :notes => String } または { :value => String } という Hash の指定と等価 (指定の notes が存在する場合は前者、しない場合は後者)

  • options (Integer) (defaults to: {})

    { :indices => Integer } という Hash の指定と等価

  • options (Hash) (defaults to: {})

    下記のとおり

Options Hash (options):

Returns:

  • (Boolean)
    true - 暦注が一致
    false - 暦注が不一致


480
481
482
# File 'lib/when_exe/inspect.rb', line 480

def note?(options={})
  _calendar_note(options).note?(self, options)
end

#notes(options = {}) ⇒ Array<Array<Hash{:note=>note, :value=>value}>>

時間位置オブジェクトの暦注を取得し value を暦注の値 (String, When::BasicTypes::M17n or When::Coordinates::Residue)とする Hash で表現

Parameters:

  • options (String) (defaults to: {})

    { :notes => String } という Hash の指定と等価

  • options (Integer) (defaults to: {})

    { :indices => Integer } という Hash の指定と等価

  • options (Hash) (defaults to: {})

    下記のとおり

Options Hash (options):

Returns:

  • (Array<Array<Hash{:note=>note, :value=>value}>>)
    note [String, When::BasicTypes::M17n

    暦注名 ]

    value [String, When::BasicTypes::M17n, When::Coordinates::Residue

    暦注の値 ]



440
441
442
# File 'lib/when_exe/inspect.rb', line 440

def notes(options={})
  _m17n_form(_notes(options), options.kind_of?(Hash) ? options : {})
end

#periodWhen::TM::PeriodDuration

分解能に対応する Duration

Returns:

Raises:

  • (ArgumentError)


691
692
693
694
695
696
# File 'lib/when_exe/tmposition.rb', line 691

def period
  return @period if @period
  period_name = When::Coordinates::PERIOD_NAME[@precision]
  raise ArgumentError, "Presicion not defined" unless period_name
  @period = When.Duration(period_name)
end

#prevWhen::TM::TemporalPosition

前の日時

Returns:



704
705
706
707
708
# File 'lib/when_exe/tmposition.rb', line 704

def prev
@precision==When::DAY ? _force_euqal_day(-1) : self-period
rescue RangeError
  (When.Calendar('Gregorian') ^ self) - period
end

#rate_of_clockNumeric

時間の歩度

Returns:



506
507
508
# File 'lib/when_exe/tmposition.rb', line 506

def rate_of_clock
  time_standard.rate_of_clock
end

#reference_labelWhen::BasicTypes::M17n

参照ラベル



203
204
205
# File 'lib/when_exe/inspect.rb', line 203

def reference_label
  [When::BasicTypes::M17n.new(self.class.to_s.split(/::/)[-1])]
end

#scan(other, leaf = false, &block) ⇒ Array of (element^self) for all When::Parts::Resource registered elements, ...

条件を満たすオブジェクトの抽出

Parameters:

Returns:

  • (Array of (element^self) for all When::Parts::Resource registered elements)

    (If other is Module)

  • (Array of (self^element) for elemnt of other which belong to the specified module or class)

    (If other is [Array])

  • (Enumerator which generates temporal position sequence begins from self with the specified duration)

    (If other is [When::TM::Duration])

  • (Array of temporal position using the specified calendar as a frame)

    (If other is [When::TM::Calendar])

  • (Array of temporal position using the specified calendar era as a calendarEraName)

    (If other is [When::TM::CalendarEra])



816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/when_exe/tmposition.rb', line 816

def scan(other, leaf=false, &block)
  list = []
  case other
  when Numeric, TemporalPosition, Position
    raise TypeError, "Operand should not be Numeric or (Temporal)Position"

  when Module
    objects = []
    ObjectSpace.each_object(other) do |object|
      objects << object if object.registered?
    end
    objects.each do |object|
      element = (object ^ self)
      if element && !(leaf && element.respond_to?(:leaf?) && !element.leaf?)
        list << element
        yield(element) if block_given?
      end
    end
    return list

  when Array
    return other.map {|v| scan(v, leaf, &block)}

  else
    if other.respond_to?(:_enumerator)
      enumerator = other._enumerator(self)
      return enumerator unless block_given?
      return enumerator.each(&block)
    end

    element = (other ^ self)
    if element && !(leaf && element.respond_to?(:leaf?) && !element.leaf?)
      list << element
      yield(element) if block_given?
    end
    if (other.respond_to?(:child) && other.child)
      other.child.each do |object|
        list += scan(object, leaf, &block)
      end
    end
    return list
  end
end

#strftime(pattern, locale = nil) ⇒ When::BasicTypes::M17n

指定の書式による多言語対応文字列化 - pattern で指定した書式で多言語対応文字列化する

Parameters:

  • pattern (When::BasicTypes::M17n)

    書式

  • locale (String, Array<String>) (defaults to: nil)

    文字列化を行う locale の指定(デフォルト : オブジェクト生成時に保持している locale すべて)

Returns:



605
606
607
608
609
610
# File 'lib/when_exe/inspect.rb', line 605

def strftime(pattern, locale=nil)
  pattern = m17n([pattern]*self.keys.length, nil, nil, {:locale=>self.keys}) if pattern.instance_of?(String)
  pattern._printf([], locale) do |k, *t|
    _strftime(k, pattern, [''])
  end
end

#succWhen::TM::TemporalPosition Also known as: next

次の日時

Returns:



716
717
718
719
720
# File 'lib/when_exe/tmposition.rb', line 716

def succ
@precision==When::DAY ? _force_euqal_day(+1) : self+period
rescue RangeError
  (When.Calendar('Gregorian') ^ self) + period
end

#term(designator, locale = nil, d = 0, e = 3) ⇒ designator に依存

strftime で扱う項の値を取得する

Parameters:

  • designator (String)

    項目名

  • locale (String) (defaults to: nil)

    文字列化を行う場合の locale の指定(デフォルト to_s(代表値))

  • d (Integer) (defaults to: 0)

    日付が‘年月日’、時刻が‘時分秒’でない表現のための桁位置変更指示

    年月に付く場合 - 大きいほうに位置をずらす
    分秒に付く場合 - 小さいほうに位置をずらす
  • e (Integer) (defaults to: 3)

    月の省略名の文字数

Returns:

  • (designator に依存)


623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
# File 'lib/when_exe/inspect.rb', line 623

def term(designator, locale=nil, d=0, e=3)
  designator = When::Parts::Locale.translate(designator,locale)
  case designator
                                                          # 現在のロケールにおける曜日の省略名
  when 'a' ; When.Resource('_co:CommonResidue::Abbr_Day')[to_i % 7].translate(locale)
                                                          # 現在のロケールにおける曜日の完全な名前
  when 'A' ; When.Resource('_co:CommonResidue::Week')[to_i % 7].label.translate(locale)
  when 'b' ; (name(MONTH-d).translate(locale))[/^.{1,#{e}}/] # 現在のロケールにおける月の省略名
  when 'B' ; (name(MONTH-d).translate(locale))            # 現在のロケールにおける月の完全な名前
  when 'C' ; year(d).div(100)                             # 世紀 (西暦年の上 2 桁)
  when 'd' ; day(d)                                       # 月内通算日
  when 'E' ; Array(calendar_era_name)[0].translate(locale)# 年号
  when 'F' ; floor(DAY).to_m17n.translate(locale)         # ISO 8601 形式の日付フォーマット
  when 'G' ; cwyear(d)                                    # ISO 8601 週単位表記の年
  when 'g' ; cwyear(d) % 100                              # ISO 8601 週単位表記の年の下2桁
  when 'H' ; hour(d)                                      # 24 時間表記での時
  when 'I' ; (hour(d)-1) % 12 + 1                         # 12 時間表記での時
  when 'j' ; yday(d)                                      # 年の初めから通算の日数
  when 'm' ; month(d)                                     # 月
  when 'M' ; minute(d)                                    # 分
  when 'p' ; (AMPM[hour(d).to_i.div(12)].translate(locale)).upcase   # 現在のロケールにおける「午前」「午後」に相当する文字列
  when 'P' ; (AMPM[hour(d).to_i.div(12)].translate(locale)).downcase # 前項を小文字で表記
  when 's' ; universal_time / Duration::SECOND      # 紀元 (1970-01-01T00:00:00Z) からの秒数
  when 'S' ; second(d)                                    # 秒 (10 進数表記)
  when 'u' ; cwday                                        # 週の何番目の日か(月曜日を 1 とする)
  when 'U' ; yweek(6, 7, d)                               # 年の初めからの通算の週番号(日曜日始まり)
  when 'V' ; cweek(d)                                     # ISO 8601 形式での年の始めからの週番号
  when 'w' ; wday                                         # 週の何番目の日 か(日曜日を 0 とする)
  when 'W' ; yweek(0, 7, d)                               # 年の初めからの通算の週番号(月曜日始まり)
  when 'y' ; year(d) % 100                                # 西暦の下2桁 (世紀部分を含まない年)
  when 'Y' ; year(d)                                      # 世紀部分を含めた ( 4 桁の) 西暦年
  when 'z' ; clock.to_basic                               # +hhmm や -hhmm の形式のタイムゾーン
  when 'Z' ; When::Parts::Locale.translate(clock.tzname[0],locale) # タイムゾーンまたはゾーン名または省略名
  else     ; designator
  end
end

#time_standardWhen::TimeStandard

時刻系

Returns:



494
495
496
497
498
499
500
# File 'lib/when_exe/tmposition.rb', line 494

def time_standard
  return @time_standard if @time_standard.kind_of?(When::TimeStandard)
  @time_standard = When.Resource(@time_standard ||
                            (clock ? clock.time_standard : nil) ||
                            (frame ? frame.time_standard : nil) ||
                            'UniversalTime', '_t:')
end

#to_clock_timeWhen::TM::ClokTime

When::TM::ClockTime オブジェクトへの変換

Returns:

  • (When::TM::ClokTime)

Raises:

  • (TypeError)


593
594
595
596
597
598
# File 'lib/when_exe/tmposition.rb', line 593

def to_clock_time
  raise TypeError, "Clock not assigned" unless clock
  clk_time = clock.to_clk_time(universal_time - (to_i - JulianDate::JD19700101)*Duration::DAY)
  clk_time.clk_time[0] += to_i
  return clk_time
end

#to_date(option = {}) ⇒ ::Date

標準ライブラリの Date オブジェクトへの変換

Parameters:

  • option (Hash) (defaults to: {})

    時間の歩度が1.0でない場合のための option see _instance

Returns:



623
624
625
626
# File 'lib/when_exe/tmposition.rb', line 623

def to_date(option={})
  return JulianDate.dynamical_time(dynamical_time, option).to_date unless rate_of_clock == 1.0
  ::Date.jd(to_i, ::Date::GREGORIAN)
end

#to_date_time(option = {:frame=>When.utc}) ⇒ ::DateTime

標準ライブラリの DateTime オブジェクトへの変換

Parameters:

  • option (Hash) (defaults to: {:frame=>When.utc})

    時間の歩度が1.0でない場合のための option see _instance

Returns:

  • (::DateTime)

Raises:

  • (TypeError)


607
608
609
610
611
612
613
614
# File 'lib/when_exe/tmposition.rb', line 607

def to_date_time(option={:frame=>When.utc})
  return JulianDate.dynamical_time(dynamical_time, option).to_date_time unless rate_of_clock == 1.0
  raise TypeError, "Clock not assigned" unless clock
  Rational
  offset   = Rational(-(clock.universal_time/Duration::SECOND).to_i, (Duration::DAY/Duration::SECOND).to_i)
  clk_time = clock.to_clk_time(universal_time - (to_i - JulianDate::JD19700101)*Duration::DAY).clk_time
  ::DateTime.jd(to_i, clk_time[1], clk_time[2], clk_time[3].to_i, offset, ::Date::GREGORIAN)
end

#to_date_uriString

URI要素化(日付のみ) - 日付の部分をURI表現の要素として用いる形式に変換

Returns:



585
586
587
# File 'lib/when_exe/inspect.rb', line 585

def to_date_uri(*args)
  _to_uri(to_s(*args).sub(/T([-+][\d:]+|Z|MTC)$/,''))
end

#to_fFloat

ユリウス日時(実数)

Returns:

  • (Float)

    universal time での経過日数を, ユリウス日と1970-01-01T00:00:00Zで時計あわせしたもの



549
550
551
# File 'lib/when_exe/tmposition.rb', line 549

def to_f
  JulianDate._t_to_d(universal_time)
end

#to_iInteger

ユリウス日(整数)

Returns:

  • (Integer)

    -4712-01-01T12:00:00Z からの経過日数に対応する通番(当該時間帯での午前0時に1進める)



559
560
561
562
563
564
# File 'lib/when_exe/tmposition.rb', line 559

def to_i
  sd  = universal_time
  sd -= @frame.universal_time if @frame.kind_of?(Clock)
  div, mod = sd.divmod(Duration::DAY)
  div + JulianDate::JD19700101
end

#to_m17nWhen::BasicTypes::M17n

多言語対応文字列化 - When.exe Standard Representation により多言語対応文字列化する



552
553
554
555
# File 'lib/when_exe/inspect.rb', line 552

def to_m17n(*args)
  return m17n(I[@indeterminated_position]) if [Unknown, Max, Min].include?(@indeterminated_position)
  return m17n(_to_s)
end

#to_residue(remainder, divisor) ⇒ When::Coordinates::Residue

剰余類化

Parameters:

  • remainder (Numeric)

    剰余

  • divisor (Integer)

    法(>0)

Returns:



575
576
577
# File 'lib/when_exe/tmposition.rb', line 575

def to_residue(remainder, divisor)
  When::Coordinates::Residue.new(remainder, divisor, {'day'=>to_i})
end

#to_sString

文字列化 - When.exe Standard Representation により文字列化する

Returns:



565
566
567
# File 'lib/when_exe/inspect.rb', line 565

def to_s(*args)
  to_m17n(*args).to_s
end

#to_time::Time

組み込みライブラリの Time オブジェクトへの変換

Returns:



632
633
634
# File 'lib/when_exe/tmposition.rb', line 632

def to_time
  time_standard.to_time_object(universal_time)
end

#to_uriString

URI要素化 - URI表現の要素として用いる形式に変換

Returns:



575
576
577
# File 'lib/when_exe/inspect.rb', line 575

def to_uri(*args)
  _to_uri(to_s(*args))
end

#universal_timeNumeric

内部時間

Returns:

  • (Numeric)

    1970-01-01T00:00:00Z からの Universal Time, Coordinated の経過時間 / 128秒

    暦法によっては、異なる意味を持つことがある



518
519
520
521
522
523
524
525
# File 'lib/when_exe/tmposition.rb', line 518

def universal_time
  case @indeterminated_position
  when Now ; time_standard.from_time_object(Time.now)
  when Max ; +Float::MAX/4
  when Min ; -Float::MAX/4
  else     ; raise NameError, "Temporal Reference System is not defined"
  end
end

#week_included(ord, wkst, opt, block) ⇒ Range, Array

Note:

引数 ord, wkst, opt はそのクラスで位置づけを判断するため、引数の順序は任意(省略も可)

含まれる週

Parameters:

  • ord (Numeric, Range)

    週の番号(default: 今週) 今週を 0 とする週番号(Integer) または週番号の範囲(Range)

    -1 - 先週
     0 - 今週
    +1 - 来週
    
  • wkst (String)

    週の開始曜日(defaultは 月曜)

  • wkst (When::CalendarTypes::CalendarNote)

    暦注オブジェクト

  • wkst (Array<When::CalendarTypes::CalendarNote, String>)

    暦注オブジェクトとそのイベントメソッド名 (暦注オブジェクトは、そのIRI文字列を指定しても良い)

  • opt (Hash)

    下記の通り

  • block (Block)

Options Hash (opt):

  • :Range (Range)

    上位繰り返し範囲(ユリウス通日…ユリウス通日)

Returns:

  • (Range)

    含まれる週を範囲として表現する Range (block 指定なし)

  • (Array)

    含まれる週の各日をブロックに渡した結果の Array (block 指定あり)



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/when_exe/inspect.rb', line 228

def week_included(*args)
  begin
    first, length, wkst, opt = _range(args, 'MO')
    case wkst
    when When::Coordinates::Residue
      today = self.floor
      begun = today.succ & wkst >> first-1
      unless @frame.equal?(begun.frame)
        begun  = (@frame ^ today).succ & wkst >> first-1
        middle = today
      end
      ended  = begun.succ & wkst >> length-1
    else
      begun = ended = nil
      if first <= 0
        it = wkst.enum_for(self.floor, :reverse)
        (1-first).times do
          begun = it.next
        end
      else
        it = wkst.enum_for(self.floor, :forward)
        first.times do
          begun = it.next
        end
      end
      it = wkst.enum_for(begun, :forward)
      (length+1).times do
        ended = it.next
      end
    end
    range = middle && block_given? ? [begun...middle, middle...ended] : [begun...ended]

  rescue RangeError
    range = [(@frame ^ self).week_included(*args)]
  end

  return range[0] unless block_given?

  (range.inject([]) {|s,r| s + r.map { |date|
    yield(date, !opt.key?(:Range) || opt[:Range].include?(date.to_i) ? DAY : nil)
  }}).unshift(yield(range[0].first, WEEK)).compact
end

#month_included(ord, wkst, opt, block) ⇒ Range, ...

Note:

引数 ord, wkst, opt はそのクラスで位置づけを判断するため、引数の順序は任意(省略も可)

含まれる年

Parameters:

  • ord (Numeric, Range)

    年の番号(default: 今年) 今年を 0 とする年番号(Integer) または年番号の範囲(Range)

    -1 - 先年
     0 - 今年
    +1 - 来年
    
  • wkst (String)

    週の開始曜日(defaultはなし)

  • wkst (When::CalendarTypes::CalendarNote)

    暦注オブジェクト

  • wkst (Array<When::CalendarTypes::CalendarNote, String>)

    暦注オブジェクトとそのイベントメソッド名 (暦注オブジェクトは、そのIRI文字列を指定しても良い)

  • opt (Hash)

    下記の通り

  • block (Block)

Options Hash (opt):

  • :Range (Range)

    上位繰り返し範囲(ユリウス通日…ユリウス通日)

Returns:

  • (Range)

    含まれる年を範囲として表現する Range (block 指定なし)

  • (Array)

    含まれる年の各日をブロックに渡した結果の Array (block 指定あり, wkst なし)

  • (Array<Array>)

    含まれる年の各日をブロックに渡した結果の 七曜表(block 指定あり, wkst あり)



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/when_exe/inspect.rb', line 353

def year_included(*args, &block)
  first, length, wkst, opt = _range(args)
  if wkst
    (first...(first+length)).map {|i|
      begun   = _force_euqal_year(i)
      ended   = _force_euqal_year(i+1)
      current = begun
      result  = [yield(begun, YEAR)]
      while current < ended do
        result << current.month_included(wkst, &block)
        current += DurationP1M
      end
      result.compact
    }
  else
    begun = _force_euqal_year(first)
    ended = _force_euqal_year(first+length)
    if block_given?
      (begun...ended).map do |date|
        yield(date)
      end
    else
      begun...ended
    end
  end
end