repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/lib/tasks/profile.rb
lib/tasks/profile.rb
def update_profile User.find_each do |user| next if user.profile profile = Profile.new profile.user = user profile.user_group = user.user_group profile.library = user.library profile.required_role = user.required_role profile.user_number = user.user_number profile.keyword_list = user.keyword_list profile.locale = user.locale profile.note = user.note profile.save! end end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/lib/tasks/reserve.rb
lib/tasks/reserve.rb
def update_reserve Reserve.find_each do |reserve| ReserveTransition.first_or_create(reserve_id: 1, sort_key: 0, to_state: reserve.state) end end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/lib/tasks/agent_type.rb
lib/tasks/agent_type.rb
def update_agent_type agent_types = YAML.safe_load(open("db/fixtures/enju_biblio/agent_types.yml").read) agent_types.each do |line| l = line[1].select! { |k, v| %w(name display_name note).include?(k) } case l["name"] when "person" agent_type = AgentType.where(name: "Person").first agent_type.update!(l) if agent_type when "corporate_body" agent_type = AgentType.where(name: "CorporateBody").first agent_type.update!(l) if agent_type end end end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/lib/enju_leaf/version.rb
lib/enju_leaf/version.rb
# frozen_string_literal: true module EnjuLeaf VERSION = "1.6.0".freeze module Version end end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/application.rb
config/application.rb
require_relative "boot" require "rails/all" require 'csv' require 'nkf' require 'rss' require_relative '../lib/enju_leaf/version' require_relative '../lib/openurl' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module EnjuLeaf class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 7.2 # Please, add to the `ignore` list any other `lib` subdirectories that do # not contain `.rb` files, or that should not be reloaded or eager loaded. # Common ones are `templates`, `generators`, or `middleware`, for example. config.add_autoload_paths_to_load_path = true config.autoload_lib(ignore: %w(assets tasks)) # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") default_locale = (ENV['ENJU_LEAF_DEFAULT_LOCALE'] || 'en').to_sym config.i18n.default_locale = default_locale config.i18n.available_locales = [default_locale, :ja, :en].uniq config.time_zone = ENV['ENJU_LEAF_TIME_ZONE'] || 'UTC' base_url = URI.parse(ENV['ENJU_LEAF_BASE_URL'] || 'http://localhost:8080') config.action_mailer.default_url_options = { host: base_url.host, protocol: base_url.scheme, port: base_url.port } config.mission_control.jobs.base_controller_class = "MissionControlController" end end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/environment.rb
config/environment.rb
# Load the Rails application. require_relative "application" # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/puma.rb
config/puma.rb
# This configuration file will be evaluated by Puma. The top-level methods that # are invoked here are part of Puma's configuration DSL. For more information # about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. # Puma starts a configurable number of processes (workers) and each process # serves each request in a thread from an internal thread pool. # # The ideal number of threads per worker depends both on how much time the # application spends waiting for IO operations and on how much you wish to # to prioritize throughput over latency. # # As a rule of thumb, increasing the number of threads will increase how much # traffic a given process can handle (throughput), but due to CRuby's # Global VM Lock (GVL) it has diminishing returns and will degrade the # response time (latency) of the application. # # The default is set to 3 threads as it's deemed a decent compromise between # throughput and latency for the average Rails application. # # Any libraries that use a connection pool or another resource pool should # be configured to provide at least as many connections as the number of # threads. This includes Active Record's `pool` parameter in `database.yml`. threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) threads threads_count, threads_count # Specifies the `port` that Puma will listen on to receive requests; default is 3000. port ENV.fetch("PORT", 3000) # Allow puma to be restarted by `bin/rails restart` command. plugin :tmp_restart # Specify the PID file. Defaults to tmp/pids/server.pid in development. # In other environments, only set the PID file if requested. pidfile ENV["PIDFILE"] if ENV["PIDFILE"]
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/routes.rb
config/routes.rb
Rails.application.routes.draw do authenticate :user, lambda {|u| u.role.try(:name) == 'Administrator' } do mount MissionControl::Jobs::Engine, at: "/jobs" end resources :manifestations resources :items resources :picture_files do get :download end resources :agents resources :manifestation_relationships resources :agent_relationships resources :resource_import_files resources :resource_import_results, only: [:index, :show, :destroy] resources :resource_export_files resources :resource_export_results, only: [:index, :show, :destroy] resources :agent_import_files resources :agent_import_results, only: [:index, :show, :destroy] resources :series_statements resources :series_statement_merges resources :series_statement_merge_lists resources :agent_merges resources :agent_merge_lists resources :import_requests resources :periodicals constraints format: :html do resources :produces resources :realizes resources :creates resources :owns resources :manifestation_relationship_types resources :agent_relationship_types resources :agent_types resources :produce_types resources :realize_types resources :create_types resources :languages resources :countries resources :licenses resources :form_of_works resources :medium_of_performances resources :identifier_types resources :budget_types resources :bookstores resources :manifestation_custom_properties resources :item_custom_properties resources :search_engines resources :frequencies resources :user_groups resources :roles end resources :carrier_types resources :content_types resources :donates resources :libraries resources :shelves resources :accepts resources :withdraws resources :subscribes resources :subscriptions resources :user_import_files resources :user_import_results, only: [:index, :show, :destroy] resources :user_export_files resources :library_groups, except: [:new, :create, :destroy] resources :profiles do post :impersonate, on: :member post :stop_impersonating, on: :collection end resource :my_account resources :iiif_presentations, only: :show, defaults: { format: :html } resources :subjects constraints format: :html do resources :subject_heading_types resources :subject_types resources :classification_types end resources :classifications resources :checkouts resources :checkouts, only: :index do put :remove_all, on: :collection end resources :checkins resources :reserves resources :user_checkout_stats resources :user_reserve_stats resources :manifestation_checkout_stats resources :manifestation_reserve_stats constraints format: :html do resources :circulation_statuses resources :use_restrictions resources :carrier_type_has_checkout_types resources :user_group_has_checkout_types resources :item_has_use_restrictions resources :checkout_types end resources :checked_items resources :baskets constraints format: :html do resources :event_categories end resources :events resources :event_import_files resources :event_import_results, only: [:index, :show, :destroy] resources :event_export_files resources :participates resources :messages do collection do post :destroy_selected end end constraints format: :html do resources :request_status_types, only: [:index, :show, :edit, :update] resources :request_types, only: [:index, :show, :edit, :update] end resources :inventories resources :inventory_files resources :ndl_books, only: [:index, :create] resources :nii_types resources :cinii_books, only: [:index, :create] resources :loc_search, only: [:index, :create] resources :bookmarks resources :tags resources :bookmark_stats resources :news_posts resources :news_feeds resources :purchase_requests do resource :order end resources :order_lists do resources :purchase_requests end resources :order_lists do resource :order end resources :orders resources :bookstores do resources :order_lists end devise_for :users get '/page/about' => 'page#about' get '/page/configuration' => 'page#configuration' get '/page/advanced_search' => 'page#advanced_search' get '/page/export' => 'page#export' get '/page/import' => 'page#import' get '/page/opensearch' => 'page#opensearch' get '/page/statistics' => 'page#statistics' get '/page/system_information' => 'page#system_information' get '/page/routing_error' => 'page#routing_error' match 'oai', to: "oai#index", via: [:get, :post] # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. # Can be used by load balancers and uptime monitors to verify that the app is live. get "up" => "rails/health#show", as: :rails_health_check # Defines the root path route ("/") root :to => "page#index" end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/spring.rb
config/spring.rb
Spring.watch( ".ruby-version", ".rbenv-vars", "tmp/restart.txt", "tmp/caching-dev.txt" )
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/sitemap.rb
config/sitemap.rb
# Set the host name for URL creation SitemapGenerator::Sitemap.default_host = URI.parse(ENV['ENJU_LEAF_BASE_URL']).to_s SitemapGenerator::Sitemap.create do # Put links creation logic here. # # The root path '/' and sitemap index file are added automatically for you. # Links are added to the Sitemap in the order they are specified. # # Usage: add(path, options={}) # (default options are used if you don't specify) # # Defaults: :priority => 0.5, :changefreq => 'weekly', # :lastmod => Time.now, :host => default_host # # Examples: # # Add '/articles' # # add articles_path, :priority => 0.7, :changefreq => 'daily' # # Add all articles: # # Article.find_each do |article| # add article_path(article), :lastmod => article.updated_at # end Manifestation.find_each do |manifestation| add manifestation_path(manifestation), lastmod: manifestation.updated_at end end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/boot.rb
config/boot.rb
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) require "bundler/setup" # Set up gems listed in the Gemfile. require "bootsnap/setup" # Speed up boot time by caching expensive operations.
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/content_security_policy.rb
config/initializers/content_security_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide content security policy. # See the Securing Rails Applications Guide for more information: # https://guides.rubyonrails.org/security.html#content-security-policy-header # Rails.application.configure do # config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # # # Generate session nonces for permitted importmap, inline scripts, and inline styles. # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } # config.content_security_policy_nonce_directives = %w(script-src style-src) # # # Report violations without enforcing the policy. # # config.content_security_policy_report_only = true # end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. # Use this to limit dissemination of sensitive information. # See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. Rails.application.config.filter_parameters += [ :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn ]
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/application_controller_renderer.rb
config/initializers/application_controller_renderer.rb
# Be sure to restart your server when you modify this file. # ActiveSupport::Reloader.to_prepare do # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # ) # end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/statesman.rb
config/initializers/statesman.rb
Statesman.configure do storage_adapter(Statesman::Adapters::ActiveRecord) end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/devise.rb
config/initializers/devise.rb
# frozen_string_literal: true # Assuming you have not yet modified this file, each configuration option below # is set to its default value. Note that some are commented out while others # are not: uncommented lines are intended to protect your configuration from # breaking changes in upgrades (i.e., in the event that future versions of # Devise change the default values for those options). # # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = '02188dd34c2442103d3f5938b73febf4e60dce4f910d9f439e0a80fd8aa91cbc983379a7a47ec3f867c3099b9cb18c5a4e91c9d46c9c4957c16c84281a4adf50' # ==> Controller configuration # Configure the parent class to the devise controllers. # config.parent_controller = 'DeviseController' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # Configure the parent class responsible to send e-mails. # config.parent_mailer = 'ActionMailer::Base' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. config.authentication_keys = [:username] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. # For API-only applications to support authentication "out-of-the-box", you will likely want to # enable this with :database unless you are using a custom strategy. # The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # When false, Devise will not attempt to reload routes on eager load. # This can reduce the time taken to boot the app but if your application # requires the Devise mappings to be loaded during boot time the application # won't boot properly. # config.reload_routes = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 12. If # using other algorithms, it sets how many times you want the password to be hashed. # The number of stretches used for generating the hashed password are stored # with the hashed password. This allows you to change the stretches without # invalidating existing passwords. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # algorithm), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 12 # Set up a pepper to generate the hashed password. # config.pepper = '1fdbd0c8cd3f16d77ebc3ecd64c0653976e491df3c33c2d450d45eafb6779e4c9ac7d2b317b6d92969bcf92c903ec6a5333bd7864b22afaf4a6f896d4b97e462' # Send a notification to the original email when the user's email is changed. # config.send_email_changed_notification = false # Send a notification email when the user's password is changed. # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. # You can also set it to nil, which will allow the user to access the website # without confirming their account. # Default is 0.days, meaning the user cannot access the website without # confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 6..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another hashing or encryption algorithm besides bcrypt (default). # You can use :sha1, :sha512 or algorithms from others authentication tools as # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 # for default behavior) and :restful_authentication_sha1 (then you should set # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' # ==> Turbolinks configuration # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: # # ActiveSupport.on_load(:devise_failure_app) do # include Turbolinks::Controller # end # ==> Configuration for :registerable # When set to false, does not sign a user in automatically after their password is # changed. Defaults to true, so a user is signed in automatically after changing a password. # config.sign_in_after_change_password = true end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/new_framework_defaults_7_2.rb
config/initializers/new_framework_defaults_7_2.rb
# Be sure to restart your server when you modify this file. # # This file eases your Rails 7.2 framework defaults upgrade. # # Uncomment each configuration one by one to switch to the new default. # Once your application is ready to run with all new defaults, you can remove # this file and set the `config.load_defaults` to `7.2`. # # Read the Guide for Upgrading Ruby on Rails for more info on each option. # https://guides.rubyonrails.org/upgrading_ruby_on_rails.html ### # Controls whether Active Job's `#perform_later` and similar methods automatically defer # the job queuing to after the current Active Record transaction is committed. # # Example: # Topic.transaction do # topic = Topic.create(...) # NewTopicNotificationJob.perform_later(topic) # end # # In this example, if the configuration is set to `:never`, the job will # be enqueued immediately, even though the `Topic` hasn't been committed yet. # Because of this, if the job is picked up almost immediately, or if the # transaction doesn't succeed for some reason, the job will fail to find this # topic in the database. # # If `enqueue_after_transaction_commit` is set to `:default`, the queue adapter # will define the behaviour. # # Note: Active Job backends can disable this feature. This is generally done by # backends that use the same database as Active Record as a queue, hence they # don't need this feature. #++ # Rails.application.config.active_job.enqueue_after_transaction_commit = :default ### # Adds image/webp to the list of content types Active Storage considers as an image # Prevents automatic conversion to a fallback PNG, and assumes clients support WebP, as they support gif, jpeg, and png. # This is possible due to broad browser support for WebP, but older browsers and email clients may still not support # WebP. Requires imagemagick/libvips built with WebP support. #++ # Rails.application.config.active_storage.web_image_content_types = %w[image/png image/jpeg image/gif image/webp] ### # Enable validation of migration timestamps. When set, an ActiveRecord::InvalidMigrationTimestampError # will be raised if the timestamp prefix for a migration is more than a day ahead of the timestamp # associated with the current time. This is done to prevent forward-dating of migration files, which can # impact migration generation and other migration commands. # # Applications with existing timestamped migrations that do not adhere to the # expected format can disable validation by setting this config to `false`. #++ # Rails.application.config.active_record.validate_migration_timestamps = true ### # Controls whether the PostgresqlAdapter should decode dates automatically with manual queries. # # Example: # ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.select_value("select '2024-01-01'::date") #=> Date # # This query used to return a `String`. #++ # Rails.application.config.active_record.postgresql_adapter_decode_dates = true ### # Enables YJIT as of Ruby 3.3, to bring sizeable performance improvements. If you are # deploying to a memory constrained environment you may want to set this to `false`. #++ # Rails.application.config.yjit = true
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/wrap_parameters.rb
config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/inflections.rb
config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, "\\1en" # inflect.singular /^(ox)en/i, "\\1" # inflect.irregular "person", "people" # inflect.uncountable %w( fish sheep ) # end ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'reserve', 'reserves' end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym "RESTful" # end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/string.rb
config/initializers/string.rb
require 'localized_name' require 'bookmark_url' class String include LocalizedName include BookmarkUrl end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/cookies_serializer.rb
config/initializers/cookies_serializer.rb
# Be sure to restart your server when you modify this file. # Specify a serializer for the signed and encrypted cookie jars. # Valid options are :json, :marshal, and :hybrid. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/permissions_policy.rb
config/initializers/permissions_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide HTTP permissions policy. For further # information see: https://developers.google.com/web/updates/2018/06/feature-policy # Rails.application.config.permissions_policy do |policy| # policy.camera :none # policy.gyroscope :none # policy.microphone :none # policy.usb :none # policy.fullscreen :self # policy.payment :self, "https://secure.example.com" # end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/assets.rb
config/initializers/assets.rb
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path Rails.application.config.assets.paths << Rails.root.join('node_modules') # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css ) Rails.application.config.assets.precompile += %w( mobile.js mobile.css print.css )
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/backtrace_silencers.rb
config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"]
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/initializers/mime_types.rb
config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf Mime::Type.register "application/octet-stream", :download Mime::Type.register "application/xml", :mods Mime::Type.register "application/rdf+xml", :rdf Mime::Type.register "application/svg+xml", :svg Mime::Type.register "text/turtle", :ttl
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/environments/test.rb
config/environments/test.rb
require "active_support/core_ext/integer/time" # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # While tests run files are not watched, reloading is not necessary. config.enable_reloading = false # Eager loading loads your entire application. When running a single test locally, # this is usually not necessary, and can slow down your test suite. However, it's # recommended that you enable it in continuous integration systems to ensure eager # loading is working properly before deploying your code. config.eager_load = ENV["CI"].present? # Configure public file server for tests with Cache-Control for performance. config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store # Render exception templates for rescuable exceptions and raise for other exceptions. config.action_dispatch.show_exceptions = :rescuable # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Store uploaded files on the local file system in a temporary directory. config.active_storage.service = :test # Disable caching for Action Mailer templates even if Action Controller # caching is enabled. config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Unlike controllers, the mailer instance doesn't have any context about the # incoming request so you'll need to provide the :host parameter yourself. config.action_mailer.default_url_options = { host: "www.example.com" } # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true config.active_job.queue_adapter = :inline config.mission_control.jobs.adapters = [ :inline, :solid_queue ] end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/environments/development.rb
config/environments/development.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded any time # it changes. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.enable_reloading = true # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable server timing. config.server_timing = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join("tmp/caching-dev.txt").exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :memory_store config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Disable caching for Action Mailer templates even if Action Controller # caching is enabled. config.action_mailer.perform_caching = false config.action_mailer.default_url_options = { host: "localhost", port: 3000 } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Highlight code that enqueued background job in logs. config.active_job.verbose_enqueue_logs = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. config.action_view.annotate_rendered_view_with_filenames = true # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. # config.generators.apply_rubocop_autocorrect_after_generate! config.active_job.queue_adapter = :solid_queue config.active_job.queue_name_prefix = "enju_leaf_development" config.solid_queue.connects_to = { database: { writing: :queue } } end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
next-l/enju_leaf
https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/config/environments/production.rb
config/environments/production.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.enable_reloading = false # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. # config.public_file_server.enabled = false # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass # Do not fall back to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = "http://assets.example.com" # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = "wss://example.com/cable" # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] # Assume all access to the app is happening through a SSL-terminating reverse proxy. # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. # config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Skip http-to-https redirect for the default health check endpoint. # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } # Log to STDOUT by default config.logger = ActiveSupport::Logger.new(STDOUT) .tap { |logger| logger.formatter = ::Logger::Formatter.new } .then { |logger| ActiveSupport::TaggedLogging.new(logger) } # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # "info" includes generic and useful information about system operation, but avoids logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). If you # want to log everything, set the level to "debug". config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") # Use a different cache store in production. config.cache_store = :solid_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). config.active_job.queue_adapter = :solid_queue config.solid_queue.connects_to = { database: { writing: :queue } } config.active_job.queue_name_prefix = "enju_leaf_production" # Disable caching for Action Mailer templates even if Action Controller # caching is enabled. config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Don't log any deprecations. config.active_support.report_deprecations = false # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Only use :id for inspections in production. config.active_record.attributes_for_inspect = [ :id ] # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ # "example.com", # Allow requests from example.com # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` # ] # Skip DNS rebinding protection for the default health check endpoint. # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } end
ruby
MIT
cd3cff6dcc8e67909e1cd0a12c38700b45af6a42
2026-01-04T17:52:15.550406Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/diweektest.rb
test/diweektest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for DIWeek class # Author:: Matthew Lipper class DIWeekTest < BaseExpressionTest def test_day_in_week_te expr = DIWeek.new(Friday) assert expr.include?(@date_20040109), "'Friday' should include #{@date_20040109} which is a Friday" assert expr.include?(@date_20040116), "'Friday' should include #{@date_20040116} which is a Friday" assert !expr.include?(@date_20040125), "'Friday' should not include #{@date_20040125} which is a Sunday" end def test_day_in_week_te_to_s assert_equal 'Friday', DIWeek.new(Friday).to_s end def test_day_in_week_dates expr = DIWeek.new(Sunday) dates = expr.dates(@date_20050101..@date_20050131) assert dates.size == 5, "There are five Sundays in January, 2005: found #{dates.size}" assert dates.include?(@date_20050102), "Should include #{@date_20050102}" assert dates.include?(@date_20050109), "Should include #{@date_20050109}" assert dates.include?(@date_20050116), "Should include #{@date_20050116}" assert dates.include?(@date_20050123), "Should include #{@date_20050123}" assert dates.include?(@date_20050130), "Should include #{@date_20050130}" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/beforetetest.rb
test/beforetetest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for BeforeTE class # Author:: Matthew Lipper class BeforeTETest < BaseExpressionTest include TExpr def test_include_inclusive expr = BeforeTE.new(@pdate_20071030, true) assert expr.include?(@date_20050101), "Should include an earlier date" assert !expr.include?(@pdate_20071114), "Should not include a later date" assert expr.include?(@pdate_20071030), "Should include the same date" end def test_include_non_inclusive expr = BeforeTE.new(@pdate_20071030) assert expr.include?(@date_20050101), "Should include an earlier date" assert !expr.include?(@pdate_20071114), "Should not include a later date" assert !expr.include?(@pdate_20071030), "Should not include the same date" end def test_to_s expr = BeforeTE.new(@pdate_20071114) assert_equal "before #{Runt.format_date(@pdate_20071114)}", expr.to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/minitest_helper.rb
test/minitest_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'runt' require 'date' require 'time' require 'rubygems' # Needed for minitest on 1.8.7 require 'minitest/autorun'
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/everytetest.rb
test/everytetest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for EveryTE class # Author:: Matthew Lipper class EveryTETest < BaseExpressionTest def test_every_other_week date = @pdate_20081112 expr = EveryTE.new(date, 14, DPrecision::DAY) assert !expr.include?(date + 7) assert expr.include?(date + 14) end def test_every_2_minutes date = @pdate_200401282100 expr=EveryTE.new(date, 2) assert expr.include?(date + 2), "Expression #{expr.to_s} should include #{(date + 2).to_s}" assert expr.include?(date + 4), "Expression #{expr.to_s} should include #{(date + 4).to_s}" assert !expr.include?(date - 2), "Expression #{expr.to_s} should not include #{(date - 2).to_s}" end def test_every_3_days # Match every 3 days begining 2007-11-14 date = @pdate_20071114 expr=EveryTE.new(date, 3) assert expr.include?(date + 6), "Expression #{expr.to_s} should include #{(date + 6).to_s}" assert expr.include?(date + 9), "Expression #{expr.to_s} should include #{(date + 9).to_s}" assert !expr.include?(date + 1), "Expression #{expr.to_s} should not include #{(date + 1).to_s}" assert !expr.include?(date - 3), "Expression #{expr.to_s} should not include #{(date - 3).to_s}" end def test_to_s date=@pdate_20071116100030 every_thirty_seconds=EveryTE.new(date, 30) assert_equal "every 30 seconds starting #{Runt.format_date(date)}", every_thirty_seconds.to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/sugartest.rb
test/sugartest.rb
#!/usr/bin/env ruby require 'minitest_helper' class SugarTest < MiniTest::Unit::TestCase include Runt def setup @date = PDate.day(2008,7,1) end def test_method_missing_should_be_called_for_invalid_name begin self.some_tuesday rescue NoMethodError # YAY! end end def test_const_should_return_runt_constant assert_equal Runt::Monday, Runt.const('monday'), \ "Expected #{Runt::Monday} but was #{Runt.const('monday')}" end def test_method_missing_should_define_dimonth make_ordinals.each do |ordinal| make_days.each do |day| name = ordinal + '_' + day result = self.send(name) expected = DIMonth.new(Runt.const(ordinal), Runt.const(day)) assert_expression expected, result end end end def test_method_missing_should_define_diweek assert_expression(DIWeek.new(Monday), self.monday) assert_expression(DIWeek.new(Tuesday), self.tuesday) assert_expression(DIWeek.new(Wednesday), self.wednesday) assert_expression(DIWeek.new(Thursday), self.thursday) assert_expression(DIWeek.new(Friday), self.friday) assert_expression(DIWeek.new(Saturday), self.saturday) assert_expression(DIWeek.new(Sunday), self.sunday) end def test_parse_time assert_equal [13,2], parse_time('1','02','pm') assert_equal [1,2], parse_time('1','02','am') end def test_method_missing_should_define_re_day assert_expression(REDay.new(8,45,14,00), daily_8_45am_to_2_00pm) end def test_method_missing_should_define_re_week make_days.each do |st_day| make_days.each do |end_day| if Runt.const(st_day) <= Runt.const(end_day) then assert_expression REWeek.new(Runt.const(st_day), \ Runt.const(end_day)), self.send('weekly_' + st_day + '_to_' + end_day) end end end end def test_method_missing_should_define_re_month assert_expression(REMonth.new(3,14), monthly_3rd_to_14th) end def test_method_missing_should_define_re_year # Imperfect but "good enough" for now make_months.each do |st_month| make_months.each do |end_month| st_mon_number = Runt.const(st_month) end_mon_number = Runt.const(end_month) next if st_mon_number > end_mon_number st_day = rand(27) + 1 end_day = rand(27) + 1 if st_mon_number == end_mon_number && st_day > end_day then st_day, end_day = end_day, st_day end #puts "Checking #{st_month} #{st_day} - #{end_month} #{end_day}" assert_expression REYear.new(st_mon_number, st_day, end_mon_number, end_day), \ self.send('yearly_' + st_month + '_' + st_day.to_s + '_to_' + end_month + '_' + end_day.to_s) end end end def test_after_should_define_after_te_with_inclusive_parameter result = self.after(@date, true) assert_expression AfterTE.new(@date, true), result assert result.instance_variable_get("@inclusive") end def test_after_should_define_after_te_without_inclusive_parameter result = self.after(@date) assert_expression AfterTE.new(@date), result assert !result.instance_variable_get("@inclusive") end def test_before_should_define_before_te_with_inclusive_parameter result = self.before(@date, true) assert_expression BeforeTE.new(@date, true), result assert result.instance_variable_get("@inclusive") end def test_before_should_define_before_te_without_inclusive_parameter result = self.before(@date) assert_expression BeforeTE.new(@date), result assert !result.instance_variable_get("@inclusive") end private def assert_expression(expected, actual) assert_equal expected.to_s, actual.to_s, \ "Expected #{expected.to_s} but was #{actual.to_s}" end def make_ordinals Runt::WEEK_OF_MONTH_ORDINALS.delete('()').split('|') end def make_days Runt::DAYS.delete('()').split('|') end def make_months Runt::MONTHS.delete('()').split('|') end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/test_runt.rb
test/test_runt.rb
require 'minitest_helper' class TestRunt < MiniTest::Unit::TestCase def test_that_it_has_a_version_number refute_nil ::Runt::VERSION end def test_it_does_something_useful #assert false end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/pdatetest.rb
test/pdatetest.rb
#!/usr/bin/env ruby require 'minitest_helper' # Unit tests for PDate class # Author:: Matthew Lipper class PDateTest < MiniTest::Unit::TestCase include Runt def setup # 2010 (August - ignored) @year_prec = PDate.year(2010,8) #August, 2004 @month_prec = PDate.month(2004,8) #January 25th, 2004 (11:39 am - ignored) @week_prec = PDate.week(2004,1,25,11,39) #January 25th, 2004 (11:39 am - ignored) @day_prec = PDate.day(2004,1,25,11,39) #11:59(:04 - ignored), December 31st, 1999 @minute_prec = PDate.min(1999,12,31,23,59,4) #12:00:10 am, March 1st, 2004 @second_prec = PDate.sec(2004,3,1,0,0,10) end def test_pdate_with_native_range start_dt = PDate.min(2013,04,22,8,0) middle_dt = PDate.min(2013,04,22,8,2) end_dt = PDate.min(2013,04,22,8,04) range = start_dt..end_dt assert(range.include?(middle_dt)) end def test_marshal # Thanks to Jodi Showers for finding/fixing this bug pdate=PDate.new(2004,2,29,22,13,2) refute_nil pdate.date_precision data=Marshal.dump pdate obj=Marshal.load data refute_nil obj.date_precision #FIXME: marshall broken in 1.9 #assert(obj.eql?(pdate)) #assert(pdate.eql?(obj)) end def test_include pdate = PDate.new(2006,3,10) assert(pdate.include?(Date.new(2006,3,10))) date = Date.new(2006,3,10) assert(date.include?(PDate.new(2006,3,10))) end def test_new date = PDate.new(2004,2,29) assert(!date.date_precision.nil?) date_time = PDate.new(2004,2,29,22,13,2) assert(!date_time.date_precision.nil?) date2 = PDate.day(2004,2,29) assert(date==date2) date_time2 = PDate.sec(2004,2,29,22,13,2) assert(date_time==date_time2) end def test_plus assert(PDate.year(2022,12)==(@year_prec+12)) assert(PDate.month(2005,2)==(@month_prec+6)) assert(PDate.week(2004,2,1)==(@week_prec+1)) assert(PDate.day(2004,2,1)==(@day_prec+7)) assert(PDate.min(2000,1,1,0,0)==(@minute_prec+1)) assert(PDate.sec(2004,3,1,0,0,21)==(@second_prec+11)) end def test_minus assert(PDate.year(1998,12)==(@year_prec-12)) assert(PDate.month(2002,6)==(@month_prec-26)) assert(PDate.week(2004,1,11)==(@week_prec-2)) #Hmmm...FIXME? @day_prec-26 == 12/31?? assert(PDate.day(2003,12,30)==(@day_prec-26)) assert(PDate.min(1999,12,31,21,57)==(@minute_prec-122)) assert(PDate.sec(2004,2,29,23,59,59)==(@second_prec-11)) end def test_spaceship_comparison_operator sec_prec = PDate.sec(2002,8,28,6,04,02) assert(PDate.year(1998,12)<sec_prec) assert(PDate.month(2002,9)>sec_prec) assert(PDate.week(2002,8,28)==sec_prec) assert(PDate.day(2002,8,28)==sec_prec) assert(PDate.min(1999,12,31,21,57)<sec_prec) assert(DateTime.new(2002,8,28,6,04,02)==sec_prec) assert(Date.new(2004,8,28)>sec_prec) end def test_succ #~ fail("FIXME! Implement succ") end def test_range #11:50 pm (:22 seconds ignored), February 2nd, 2004 min1 = PDate.min(2004,2,29,23,50,22) #12:02 am , March 1st, 2004 min2 = PDate.min(2004,3,1,0,2) #Inclusive Range w/minute precision r_min = min1..min2 assert( r_min.include?(PDate.min(2004,2,29,23,50,22)) ) assert( r_min.include?(PDate.min(2004,3,1,0,2)) ) assert( r_min.include?(PDate.min(2004,3,1,0,0)) ) assert( ! r_min.include?(PDate.min(2004,3,1,0,3)) ) #Exclusive Range w/minute precision r_min = min1...min2 assert( r_min.include?(PDate.min(2004,2,29,23,50,22)) ) assert( !r_min.include?(PDate.min(2004,3,1,0,2)) ) end def test_create_with_class_methods #December 12th, 1968 no_prec = PDate.civil(1968,12,12) #December 12th, 1968 (at 11:15 am - ignored) day_prec = PDate.day(1968,12,12,11,15) assert(no_prec==day_prec, "PDate instance does not equal precisioned instance.") #December 2004 (24th - ignored) month_prec1 = PDate.month(2004,12,24) #December 31st, 2004 (31st - ignored) month_prec2 = PDate.month(2004,12,31) assert(month_prec1==month_prec2, "PDate.month instances not equal.") #December 2004 month_prec3 = PDate.month(2004,12) assert(month_prec1==month_prec3, "PDate.month instances not equal.") assert(month_prec2==month_prec3, "PDate.month instances not equal.") #December 2003 month_prec4 = PDate.month(2003,12) assert(month_prec4!=month_prec1, "PDate.month instances not equal.") one_week = [ PDate.week(2004, 12, 20), # Monday PDate.week(2004, 12, 21), # Tuesday PDate.week(2004, 12, 22), # Wednesday PDate.week(2004, 12, 23), # Thursday PDate.week(2004, 12, 24), # Friday PDate.week(2004, 12, 25), # Saturday PDate.week(2004, 12, 26), # Sunday ] one_week.each do |week_prec1| one_week.each do |week_prec2| assert_equal week_prec1, week_prec2 end end week_before = PDate.week(2004, 12, 19) week_after = PDate.week(2004, 12, 27) one_week.each do |week_prec| assert week_prec != week_before assert week_prec != week_after end end def test_parse_with_precision month_parsed = PDate.parse('April 2004', :precision => PDate::MONTH) assert_equal month_parsed, PDate.month(2004,04) refute_equal month_parsed, PDate.year(2004,04) end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/icalendartest.rb
test/icalendartest.rb
#!/usr/bin/env ruby require 'minitest_helper' # RFC 2445 is the iCalendar specification. It includes dozens of # specific examples that make great tests for Runt temporal expressions. class ICalendarTest < MiniTest::Unit::TestCase include Runt # "Daily for 10 occurences" def test_example_1 start_date = DateTime.parse("US-Eastern:19970902T090000") #Sep 2, 1997 end_date = start_date + 365 #Sep 2, 1998 #rrule = RecurrenceRule.new("FREQ=DAILY;COUNT=10") te = REWeek.new(Sun, Sat) expected = ICalendarTest.get_date_range(start_date, DateTime.parse("US-Eastern:19970911T090000")) results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end # "Daily until December 24, 1997" def test_example_2 start_date = DateTime.parse("US-Eastern:19970902T090000") #Sep 2, 1997 end_date = start_date + 365 #rrule = RecurrenceRule.new("FREQ=DAILY;UNTIL=19971224T000000Z") te = BeforeTE.new(DateTime.parse("19971224T090000"), true) & REWeek.new(Sun, Sat) expected = ICalendarTest.get_date_range(start_date, DateTime.parse("19971224T090000")) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Every other day - forever" def test_example_3 start_date = DateTime.parse("US-Eastern:19970902T090000") #Sep 2 end_date = DateTime.parse("US-Eastern:19971003T090000") #Oct 3 #rrule = RecurrenceRule.new("FREQ=DAILY;INTERVAL=2") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970904T090000"), #Sep 4 DateTime.parse("US-Eastern:19970906T090000"), #Sep 6 DateTime.parse("US-Eastern:19970908T090000"), #Sep 8 DateTime.parse("US-Eastern:19970910T090000"), #Sep 10 DateTime.parse("US-Eastern:19970912T090000"), #Sep 12 DateTime.parse("US-Eastern:19970914T090000"), #Sep 14 DateTime.parse("US-Eastern:19970916T090000"), #Sep 16 DateTime.parse("US-Eastern:19970918T090000"), #Sep 18 DateTime.parse("US-Eastern:19970920T090000"), #Sep 20 DateTime.parse("US-Eastern:19970922T090000"), #Sep 22 DateTime.parse("US-Eastern:19970924T090000"), #Sep 24 DateTime.parse("US-Eastern:19970926T090000"), #Sep 26 DateTime.parse("US-Eastern:19970928T090000"), #Sep 28 DateTime.parse("US-Eastern:19970930T090000"), #Sep 30 DateTime.parse("US-Eastern:19971002T090000"), #Oct 02 ] te = REWeek.new(Sun,Sat) & EveryTE.new(start_date, 2, DPrecision::DAY) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) #alternatively we could use the DayIntervalTE te = DayIntervalTE.new(start_date, 2) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Every 10 days, 5 occurrences" def test_example_4 start_date = DateTime.parse("US-Eastern:19970902T090000") #Sep 2, 1997 end_date = start_date + 180 #Mar 1, 1998 (halved the normal test range because EveryTE is pretty slow) #rrule = RecurrenceRule.new("FREQ=DAILY;INTERVAL=10;COUNT=5") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970912T090000"), #Sep 12 DateTime.parse("US-Eastern:19970922T090000"), #Sep 22 DateTime.parse("US-Eastern:19971002T090000"), #Oct 2 DateTime.parse("US-Eastern:19971012T090000"), #Oct 12 ] te = REWeek.new(Sun,Sat) & EveryTE.new(start_date, 10, DPrecision::DAY) results = te.dates(DateRange.new(start_date, end_date), 5) assert_equal(expected, results) #alternatively we could use the DayIntervalTE te = DayIntervalTE.new(start_date, 10) results = te.dates(DateRange.new(start_date, end_date), 5 ) assert_equal(expected, results) end # "Every day in January, for 3 years" (first example, yearly byday) def test_example_5_a start_date = DateTime.parse("US-Eastern:19980101T090000") #Jan 1, 1998 end_date = start_date + 365 + 365 + 366 + 31 #Feb 1, 2001 #rrule = RecurrenceRule.new("FREQ=YEARLY;UNTIL=20000131T090000Z;BYMONTH=1;BYDAY=SU,MO,TU,WE,TH,FR,SA") expected = [] expected += ICalendarTest.get_date_range(DateTime.parse("US-Eastern:19980101T090000"), DateTime.parse("US-Eastern:19980131T090000")) expected += ICalendarTest.get_date_range(DateTime.parse("US-Eastern:19990101T090000"), DateTime.parse("US-Eastern:19990131T090000")) expected += ICalendarTest.get_date_range(DateTime.parse("US-Eastern:20000101T090000"), DateTime.parse("US-Eastern:20000131T090000")) te = BeforeTE.new(DateTime.parse("20000131T090000"), true) & REYear.new(1) & (DIWeek.new(Sun) | DIWeek.new(Mon) | DIWeek.new(Tue) | DIWeek.new(Wed) | DIWeek.new(Thu) | DIWeek.new(Fri) | DIWeek.new(Sat)) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Every day in January, for 3 years" (second example, daily bymonth) def test_example_5_b start_date = DateTime.parse("US-Eastern:19980101T090000") end_date = start_date + 365 + 365 + 366 + 31 #Feb 1, 2001 #rrule = RecurrenceRule.new("FREQ=DAILY;UNTIL=20000131T090000Z;BYMONTH=1") expected = [] expected += ICalendarTest.get_date_range(DateTime.parse("US-Eastern:19980101T090000"), DateTime.parse("US-Eastern:19980131T090000")) expected += ICalendarTest.get_date_range(DateTime.parse("US-Eastern:19990101T090000"), DateTime.parse("US-Eastern:19990131T090000")) expected += ICalendarTest.get_date_range(DateTime.parse("US-Eastern:20000101T090000"), DateTime.parse("US-Eastern:20000131T090000")) te = BeforeTE.new(DateTime.parse("20000131T090000"), true) & REWeek.new(Sun, Sat) & REYear.new(1) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Weekly for 10 occurrences" def test_example_6 start_date = DateTime.parse("US-Eastern:19970902T090000") # Sep 2nd, 1997 end_date = start_date + 365 #Sep 2, 1998 #rrule = RecurrenceRule.new("FREQ=WEEKLY;COUNT=10") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970909T090000"), #Sep 9 DateTime.parse("US-Eastern:19970916T090000"), #Sep 16 DateTime.parse("US-Eastern:19970923T090000"), #Sep 23 DateTime.parse("US-Eastern:19970930T090000"), #Sep 30 DateTime.parse("US-Eastern:19971007T090000"), #Oct 7 DateTime.parse("US-Eastern:19971014T090000"), #Oct 14 DateTime.parse("US-Eastern:19971021T090000"), #Oct 21 DateTime.parse("US-Eastern:19971028T090000"), #Oct 28 DateTime.parse("US-Eastern:19971104T090000"), #Nov 4 ] te = EveryTE.new(start_date, 7, DPrecision::DAY) results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end # "Weekly until December 24th, 1997" def test_example_7 start_date = DateTime.parse("US-Eastern:19970902T090000") # Sep 2nd, 1997 end_date = start_date + 365 #Sep 2, 1998 #rrule = RecurrenceRule.new("FREQ=WEEKLY;UNTIL=19971224T000000Z") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970909T090000"), #Sep 9 DateTime.parse("US-Eastern:19970916T090000"), #Sep 16 DateTime.parse("US-Eastern:19970923T090000"), #Sep 23 DateTime.parse("US-Eastern:19970930T090000"), #Sep 30 DateTime.parse("US-Eastern:19971007T090000"), #Oct 7 DateTime.parse("US-Eastern:19971014T090000"), #Oct 14 DateTime.parse("US-Eastern:19971021T090000"), #Oct 21 DateTime.parse("US-Eastern:19971028T090000"), #Oct 28 DateTime.parse("US-Eastern:19971104T090000"), #Nov 4 DateTime.parse("US-Eastern:19971111T090000"), #Nov 11 DateTime.parse("US-Eastern:19971118T090000"), #Nov 18 DateTime.parse("US-Eastern:19971125T090000"), #Nov 25 DateTime.parse("US-Eastern:19971202T090000"), #Dec 2 DateTime.parse("US-Eastern:19971209T090000"), #Dec 9 DateTime.parse("US-Eastern:19971216T090000"), #Dec 16 DateTime.parse("US-Eastern:19971223T090000"), #Dec 23 ] te = BeforeTE.new(DateTime.parse("19971224T000000"), true) & EveryTE.new(start_date, 7, DPrecision::DAY) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Every other week - forever" def test_example_8 start_date = DateTime.parse("US-Eastern:19970902T090000") # Sep 2nd, 1997 end_date = DateTime.parse("US-Eastern:19980201T090000") # Feb 1st, 1998 #rrule = RecurrenceRule.new("FREQ=WEEKLY;INTERVAL=2;WKST=SU") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970916T090000"), #Sep 16 DateTime.parse("US-Eastern:19970930T090000"), #Sep 30 DateTime.parse("US-Eastern:19971014T090000"), #Oct 14 DateTime.parse("US-Eastern:19971028T090000"), #Oct 28 DateTime.parse("US-Eastern:19971111T090000"), #Nov 11 DateTime.parse("US-Eastern:19971125T090000"), #Nov 25 DateTime.parse("US-Eastern:19971209T090000"), #Dec 9 DateTime.parse("US-Eastern:19971223T090000"), #Dec 23 DateTime.parse("US-Eastern:19980106T090000"), #Jan 6 DateTime.parse("US-Eastern:19980120T090000"), #Jan 20 ] te = EveryTE.new(start_date, 7*2, DPrecision::DAY) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Weekly on Tuesday and Thursday for 5 weeks (first example, using until)" def test_example_9_a start_date = DateTime.parse("US-Eastern:19970902T090000") # Sep 2nd, 1997 end_date = DateTime.parse("US-Eastern:19980101T090000") # Jan 1st, 1998 #rrule = RecurrenceRule.new("FREQ=WEEKLY;UNTIL=19971007T000000Z;WKST=SU;BYDAY=TU,TH") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970904T090000"), #Sep 4 DateTime.parse("US-Eastern:19970909T090000"), #Sep 9 DateTime.parse("US-Eastern:19970911T090000"), #Sep 11 DateTime.parse("US-Eastern:19970916T090000"), #Sep 16 DateTime.parse("US-Eastern:19970918T090000"), #Sep 18 DateTime.parse("US-Eastern:19970923T090000"), #Sep 23 DateTime.parse("US-Eastern:19970925T090000"), #Sep 25 DateTime.parse("US-Eastern:19970930T090000"), #Sep 30 DateTime.parse("US-Eastern:19971002T090000"), #Oct 2 ] te = BeforeTE.new(DateTime.parse("19971007T000000Z"), true) & (DIWeek.new(Tue) | DIWeek.new(Thu)) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Weekly on Tuesday and Thursday for 5 weeks (second example, using count)" def test_example_9_b start_date = DateTime.parse("US-Eastern:19970902T090000") # Sep 2nd, 1997 end_date = DateTime.parse("US-Eastern:19980101T090000") # Jan 1st, 1998 #rrule = RecurrenceRule.new("FREQ=WEEKLY;COUNT=10;WKST=SU;BYDAY=TU,TH") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970904T090000"), #Sep 4 DateTime.parse("US-Eastern:19970909T090000"), #Sep 9 DateTime.parse("US-Eastern:19970911T090000"), #Sep 11 DateTime.parse("US-Eastern:19970916T090000"), #Sep 16 DateTime.parse("US-Eastern:19970918T090000"), #Sep 18 DateTime.parse("US-Eastern:19970923T090000"), #Sep 23 DateTime.parse("US-Eastern:19970925T090000"), #Sep 25 DateTime.parse("US-Eastern:19970930T090000"), #Sep 30 DateTime.parse("US-Eastern:19971002T090000"), #Oct 2 ] te = DIWeek.new(Tue) | DIWeek.new(Thu) results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end # "Every other week on Monday, Wednesday, and Friday until December 24, 1997 # but starting on Tuesday, September 2, 1997" def test_example_10 start_date = DateTime.parse("US-Eastern:19970902T090000") # Sep 2nd, 1997 end_date = DateTime.parse("US-Eastern:19980201T090000") # Feb 1st, 1998 #rrule = RecurrenceRule.new("FREQ=WEEKLY;INTERVAL=2;UNTIL=19971224T000000Z;WKST=SU;BYDAY=MO,WE,FR") expected = [ #LJK: note that Sep 2nd is listed in the example, but it does not match the given RRULE. # It definitely is not rendered by the TE below, so I'm just commenting it out for more research. #DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970903T090000"), #Sep 3 DateTime.parse("US-Eastern:19970905T090000"), #Sep 5 DateTime.parse("US-Eastern:19970915T090000"), #Sep 15 DateTime.parse("US-Eastern:19970917T090000"), #Sep 17 DateTime.parse("US-Eastern:19970919T090000"), #Sep 19 DateTime.parse("US-Eastern:19970929T090000"), #Sep 29 DateTime.parse("US-Eastern:19971001T090000"), #Oct 1 DateTime.parse("US-Eastern:19971003T090000"), #Oct 3 DateTime.parse("US-Eastern:19971013T090000"), #Oct 13 DateTime.parse("US-Eastern:19971015T090000"), #Oct 15 DateTime.parse("US-Eastern:19971017T090000"), #Oct 17 DateTime.parse("US-Eastern:19971027T090000"), #Oct 27 DateTime.parse("US-Eastern:19971029T090000"), #Oct 29 DateTime.parse("US-Eastern:19971031T090000"), #Oct 31 DateTime.parse("US-Eastern:19971110T090000"), #Nov 10 DateTime.parse("US-Eastern:19971112T090000"), #Nov 12 DateTime.parse("US-Eastern:19971114T090000"), #Nov 14 DateTime.parse("US-Eastern:19971124T090000"), #Nov 24 DateTime.parse("US-Eastern:19971126T090000"), #Nov 26 DateTime.parse("US-Eastern:19971128T090000"), #Nov 28 DateTime.parse("US-Eastern:19971208T090000"), #Dec 8 DateTime.parse("US-Eastern:19971210T090000"), #Dec 10 DateTime.parse("US-Eastern:19971212T090000"), #Dec 12 DateTime.parse("US-Eastern:19971222T090000"), #Dec 22 ] te = BeforeTE.new(DateTime.parse("19971224T000000Z"), true) & (DIWeek.new(Mon) | DIWeek.new(Wed) | DIWeek.new(Fri)) & EveryTE.new(start_date, 2, DPrecision::WEEK) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Every other week on Tuesday and Thursday, for 8 occurences" def test_example_11 start_date = DateTime.parse("US-Eastern:19970902T090000") # Sep 2nd, 1997 end_date = DateTime.parse("US-Eastern:19980201T090000") # Feb 1st, 1998 #rrule = RecurrenceRule.new("FREQ=WEEKLY;INTERVAL=2;COUNT=8;WKST=SU;BYDAY=TU,TH") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970904T090000"), #Sep 4 DateTime.parse("US-Eastern:19970916T090000"), #Sep 16 DateTime.parse("US-Eastern:19970918T090000"), #Sep 18 DateTime.parse("US-Eastern:19970930T090000"), #Sep 30 DateTime.parse("US-Eastern:19971002T090000"), #Oct 2 DateTime.parse("US-Eastern:19971014T090000"), #Oct 14 DateTime.parse("US-Eastern:19971016T090000"), #Oct 16 ] te = EveryTE.new(start_date, 2, DPrecision::WEEK) & (DIWeek.new(Tue) | DIWeek.new(Thu)) results = te.dates(DateRange.new(start_date, end_date), 8) assert_equal(expected, results) end # "Monthly on the 1st Friday for ten occurences" def test_example_12 start_date = DateTime.parse("US-Eastern:19970905T090000") #Sep 5, 1997 end_date = start_date + 365 #Sep 5, 1998 #rrule = RecurrenceRule.new("FREQ=MONTHLY;COUNT=10;BYDAY=1FR") expected = [ DateTime.parse("US-Eastern:19970905T090000"), #Sep 5 DateTime.parse("US-Eastern:19971003T090000"), #Oct 3 DateTime.parse("US-Eastern:19971107T090000"), #Nov 7 DateTime.parse("US-Eastern:19971205T090000"), #Dec 5 DateTime.parse("US-Eastern:19980102T090000"), #Jan 2 DateTime.parse("US-Eastern:19980206T090000"), #Feb 6 DateTime.parse("US-Eastern:19980306T090000"), #Mar 6 DateTime.parse("US-Eastern:19980403T090000"), #Apr 3 DateTime.parse("US-Eastern:19980501T090000"), #May 1 DateTime.parse("US-Eastern:19980605T090000"), #Jun 5 ] te = DIMonth.new(1,5) #first friday results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end # "Monthly on the 1st Friday until December 24, 1997" def test_example_13 start_date = DateTime.parse("US-Eastern:19970905T090000") #Sep 5, 1997 end_date = start_date + 365 #Sep 5, 1998 #rrule = RecurrenceRule.new("FREQ=MONTHLY;UNTIL=19971224T000000;BYDAY=1FR") expected = [ DateTime.parse("US-Eastern:19970905T090000"), #Sep 5 DateTime.parse("US-Eastern:19971003T090000"), #Oct 3 DateTime.parse("US-Eastern:19971107T090000"), #Nov 7 DateTime.parse("US-Eastern:19971205T090000"), #Dec 5 ] te = BeforeTE.new(DateTime.parse("US-Eastern:19971224T000000")) & DIMonth.new(1,5) #first friday results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Every other month on the 1st and last Sunday of the month for 10 occurences" def test_example_14 start_date = DateTime.parse("US-Eastern:19970907T090000") #Sep 7, 1997 end_date = start_date + 365 #Sep 7, 1998 #rrule = RecurrenceRule.new("FREQ=MONTHLY;INTERVAL=2;COUNT=10;BYDAY=1SU,-1SU") expected = [ DateTime.parse("US-Eastern:19970907T090000"), #Sep 5 DateTime.parse("US-Eastern:19970928T090000"), #Sep 28 DateTime.parse("US-Eastern:19971102T090000"), #Nov 2 DateTime.parse("US-Eastern:19971130T090000"), #Nov 30 DateTime.parse("US-Eastern:19980104T090000"), #Jan 4 DateTime.parse("US-Eastern:19980125T090000"), #Jan 25 DateTime.parse("US-Eastern:19980301T090000"), #Mar 1 DateTime.parse("US-Eastern:19980329T090000"), #Mar 29 DateTime.parse("US-Eastern:19980503T090000"), #May 3 DateTime.parse("US-Eastern:19980531T090000"), #May 31 ] te = EveryTE.new(start_date, 2, DPrecision::MONTH) & (DIMonth.new(1,0) | DIMonth.new(-1,0)) #first and last Sundays results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end # "Monthly on the second to last Monday of the month for 6 months" def test_example_15 start_date = DateTime.parse("US-Eastern:19970922T090000") #Sep 22, 1997 end_date = start_date + 365 #Sep 22, 1998 #rrule = RecurrenceRule.new("FREQ=MONTHLY;COUNT=6;BYDAY=-2MO") expected = [ DateTime.parse("US-Eastern:19970922T090000"), #Sep 22 DateTime.parse("US-Eastern:19971020T090000"), #Oct 20 DateTime.parse("US-Eastern:19971117T090000"), #Nov 17 DateTime.parse("US-Eastern:19971222T090000"), #Dec 22 DateTime.parse("US-Eastern:19980119T090000"), #Jan 19 DateTime.parse("US-Eastern:19980216T090000"), #Feb 16 ] te = DIMonth.new(-2,1) #second to last Monday results = te.dates(DateRange.new(start_date, end_date), 6) assert_equal(expected, results) end =begin #### NOTE: Runt does not currently support negative day of month references! # "Monthly on the third to the last day of the month, forever" def test_example_16 start_date = DateTime.parse("US-Eastern:19970922T090000") #Sep 22, 1997 end_date = DateTime.parse("US-Eastern:19980301T090000"), #Mar 1, 1998 #rrule = RecurrenceRule.new("FREQ=MONTHLY;BYMONTHDAY=-3") expected = [ DateTime.parse("US-Eastern:19970928T090000"), #Sep 28 DateTime.parse("US-Eastern:19971029T090000"), #Oct 29 DateTime.parse("US-Eastern:19971128T090000"), #Nov 28 DateTime.parse("US-Eastern:19971229T090000"), #Dec 29 DateTime.parse("US-Eastern:19980129T090000"), #Jan 29 DateTime.parse("US-Eastern:19980226T090000"), #Feb 26 ] te = REMonth.new(-3) #third to last day of the month results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end =end # "Monthly on the 2nd and 15th of the month for 10 occurences" def test_example_17 start_date = DateTime.parse("US-Eastern:19970902T090000") #Sep 2, 1997 end_date = start_date + 365 #Sep 2, 1998 #rrule = RecurrenceRule.new("FREQ=MONTHLY;COUNT=10;BYMONTHDAY=2,15") expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 2 DateTime.parse("US-Eastern:19970915T090000"), #Sep 15 DateTime.parse("US-Eastern:19971002T090000"), #Oct 2 DateTime.parse("US-Eastern:19971015T090000"), #Oct 15 DateTime.parse("US-Eastern:19971102T090000"), #Nov 2 DateTime.parse("US-Eastern:19971115T090000"), #Nov 15 DateTime.parse("US-Eastern:19971202T090000"), #Dec 2 DateTime.parse("US-Eastern:19971215T090000"), #Dec 15 DateTime.parse("US-Eastern:19980102T090000"), #Jan 2 DateTime.parse("US-Eastern:19980115T090000"), #Jan 15 ] te = REMonth.new(2) | REMonth.new(15) #second or fifteenth of the month results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end =begin #### NOTE: Runt does not currently support negative day of month references! # "Monthly on the first and last day of the month for 10 occurences" def test_example_18 start_date = DateTime.parse("US-Eastern:19970930T090000") #Sep 30, 1997 end_date = start_date + 365 #Sep 30, 1998 #rrule = RecurrenceRule.new("FREQ=MONTHLY;COUNT=10;BYMONTHDAY=1,-1") expected = [ DateTime.parse("US-Eastern:19970930T090000"), #Sep 30 DateTime.parse("US-Eastern:19971001T090000"), #Oct 1 DateTime.parse("US-Eastern:19971031T090000"), #Oct 31 DateTime.parse("US-Eastern:19971101T090000"), #Nov 1 DateTime.parse("US-Eastern:19971130T090000"), #Nov 30 DateTime.parse("US-Eastern:19971201T090000"), #Dec 1 DateTime.parse("US-Eastern:19971231T090000"), #Dec 31 DateTime.parse("US-Eastern:19980101T090000"), #Jan 1 DateTime.parse("US-Eastern:19980131T090000"), #Jan 31 DateTime.parse("US-Eastern:19980201T090000"), #Feb 1 ] te = REMonth.new(1) | REMonth.new(-1) #first and last days of the month results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end =end # "Every 18 months on the 10th thru 15th of the month for 10 occurrences" def test_example_19 start_date = DateTime.parse("US-Eastern:19970910T090000") #Sep 10, 1997 end_date = start_date + 365 + 365 #Sep 10, 1999 #rrule = RecurrenceRule.new("FREQ=MONTHLY;INTERVAL=18;COUNT=10;BYMONTHDAY=10,11,12,13,14,15") expected = [ DateTime.parse("US-Eastern:19970910T090000"), #Sep 10, 1997 DateTime.parse("US-Eastern:19970911T090000"), #Sep 11, 1997 DateTime.parse("US-Eastern:19970912T090000"), #Sep 12, 1997 DateTime.parse("US-Eastern:19970913T090000"), #Sep 13, 1997 DateTime.parse("US-Eastern:19970914T090000"), #Sep 14, 1997 DateTime.parse("US-Eastern:19970915T090000"), #Sep 15, 1997 DateTime.parse("US-Eastern:19990310T090000"), #Mar 10, 1999 DateTime.parse("US-Eastern:19990311T090000"), #Mar 11, 1999 DateTime.parse("US-Eastern:19990312T090000"), #Mar 12, 1999 DateTime.parse("US-Eastern:19990313T090000"), #Mar 13, 1999 ] te = REMonth.new(10,15) & EveryTE.new(start_date, 18, DPrecision::MONTH) #tenth through the fifteenth results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end # "Every Tuesday, every other month" def test_example_20 start_date = DateTime.parse("US-Eastern:19970902T090000") #Sep 2, 1997 end_date = start_date + 220 #Oct 4, 1998 #rrule = RecurrenceRule.new("FREQ=MONTHLY;INTERVAL=2;BYDAY=TU) expected = [ DateTime.parse("US-Eastern:19970902T090000"), #Sep 02, 1997 DateTime.parse("US-Eastern:19970909T090000"), #Sep 09, 1997 DateTime.parse("US-Eastern:19970916T090000"), #Sep 16, 1997 DateTime.parse("US-Eastern:19970923T090000"), #Sep 23, 1997 DateTime.parse("US-Eastern:19970930T090000"), #Sep 30, 1997 DateTime.parse("US-Eastern:19971104T090000"), #Nov 04, 1997 DateTime.parse("US-Eastern:19971111T090000"), #Nov 11, 1997 DateTime.parse("US-Eastern:19971118T090000"), #Nov 18, 1997 DateTime.parse("US-Eastern:19971125T090000"), #Nov 25, 1997 DateTime.parse("US-Eastern:19980106T090000"), #Jan 06, 1998 DateTime.parse("US-Eastern:19980113T090000"), #Jan 13, 1998 DateTime.parse("US-Eastern:19980120T090000"), #Jan 20, 1998 DateTime.parse("US-Eastern:19980127T090000"), #Jan 27, 1998 DateTime.parse("US-Eastern:19980303T090000"), #Mar 03, 1998 DateTime.parse("US-Eastern:19980310T090000"), #Mar 10, 1998 DateTime.parse("US-Eastern:19980317T090000"), #Mar 17, 1998 DateTime.parse("US-Eastern:19980324T090000"), #Mar 24, 1998 DateTime.parse("US-Eastern:19980331T090000"), #Mar 31, 1998 ] te = EveryTE.new(start_date, 2, DPrecision::MONTH) & DIWeek.new(Tuesday) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Yearly in June and July for 10 occurrences" def test_example_21 start_date = DateTime.parse("US-Eastern:19970610T090000") #June 10, 1997 end_date = DateTime.parse("US-Eastern:20020725T090000") #July 25, 2002 #rrule = RecurrenceRule.new("FREQ=YEARLY;COUNT=10;BYMONTH=6,7) expected = [ DateTime.parse("US-Eastern:19970610T090000"), #Jun 10, 1997 DateTime.parse("US-Eastern:19970710T090000"), #Jul 10, 1997 DateTime.parse("US-Eastern:19980610T090000"), #Jun 10, 1998 DateTime.parse("US-Eastern:19980710T090000"), #Jul 10, 1998 DateTime.parse("US-Eastern:19990610T090000"), #Jun 10, 1999 DateTime.parse("US-Eastern:19990710T090000"), #Jul 10, 1999 DateTime.parse("US-Eastern:20000610T090000"), #Jun 10, 2000 DateTime.parse("US-Eastern:20000710T090000"), #Jul 10, 2000 DateTime.parse("US-Eastern:20010610T090000"), #Jun 10, 2001 DateTime.parse("US-Eastern:20010710T090000"), #Jul 10, 2001 ] te = (REYear.new(6) | REYear.new(7)) & REMonth.new(start_date.day) results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end # "Every other year on January, February, and March for 10 occurrences" def test_example_22 start_date = DateTime.parse("US-Eastern:19970310T090000") #Mar 10, 1997 end_date = DateTime.parse("US-Eastern:20040401T090000") #Apr 1, 2004 #rrule = RecurrenceRule.new("FREQ=YEARLY;INTERVAL=2;COUNT=10;BYMONTH=1,2,3") expected = [ DateTime.parse("US-Eastern:19970310T090000"), #Mar 10, 1997 DateTime.parse("US-Eastern:19990110T090000"), #Jan 10, 1999 DateTime.parse("US-Eastern:19990210T090000"), #Feb 10, 1999 DateTime.parse("US-Eastern:19990310T090000"), #Mar 10, 1999 DateTime.parse("US-Eastern:20010110T090000"), #Jan 10, 2001 DateTime.parse("US-Eastern:20010210T090000"), #Feb 10, 2001 DateTime.parse("US-Eastern:20010310T090000"), #Mar 10, 2001 DateTime.parse("US-Eastern:20030110T090000"), #Jan 10, 2003 DateTime.parse("US-Eastern:20030210T090000"), #Feb 10, 2003 DateTime.parse("US-Eastern:20030310T090000"), #Mar 10, 2003 ] te = REMonth.new(start_date.day) & (REYear.new(1) | REYear.new(2) | REYear.new(3)) & EveryTE.new(start_date, 2, DPrecision::YEAR) results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end =begin # "Every 3rd year on the 1st, 100th, and 200th day for 10 occurrences" def test_example_23 start_date = DateTime.parse("US-Eastern:19970101T090000") #Jan 1, 1997 end_date = DateTime.parse("US-Eastern:20070401T090000") #Apr 1, 2007 #rrule = RecurrenceRule.new("FREQ=YEARLY;INTERVAL=3;COUNT=10;BYYEARDAY=1,100,200") expected = [ DateTime.parse("US-Eastern:19970101T090000"), #Jan 1, 1997 DateTime.parse("US-Eastern:19970410T090000"), #Apr 10, 1997 DateTime.parse("US-Eastern:19970719T090000"), #Jul 19, 1997 DateTime.parse("US-Eastern:20000101T090000"), #Jan 1, 2000 DateTime.parse("US-Eastern:20000409T090000"), #Apr 9, 2000 DateTime.parse("US-Eastern:20000718T090000"), #Jul 18, 2000 DateTime.parse("US-Eastern:20030101T090000"), #Jan 1, 2003 DateTime.parse("US-Eastern:20030410T090000"), #Apr 10, 2003 DateTime.parse("US-Eastern:20030719T090000"), #Jul 19, 2003 DateTime.parse("US-Eastern:20060101T090000"), #Jan 1, 2006 ] te = EveryTE.new(start_date, 3, DPrecision::YEAR) & (REYear.new(6) | REYear.new(7)) & REMonth.new(start_date.day) results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end # "Every 20th Monday of the year, forever" def test_example_24 start_date = DateTime.parse("US-Eastern:19970519T090000") #May 19, 1997 end_date = DateTime.parse("US-Eastern:20000101T090000") #Jan 1, 2000 #rrule = RecurrenceRule.new("FREQ=YEARLY;BYDAY=20MO") expected = [ DateTime.parse("US-Eastern:19970519T090000"), #May 19, 1997 DateTime.parse("US-Eastern:19980518T090000"), #May 18, 1998 DateTime.parse("US-Eastern:19990517T090000"), #May 17, 1999 ] te = (REYear.new(6) | REYear.new(7)) & REMonth.new(start_date.day) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Monday of week number 20 (where the default start of the week is Monday), forever" def test_example_25 start_date = DateTime.parse("US-Eastern:19970512T090000") #May 12, 1997 end_date = DateTime.parse("US-Eastern:20000101T090000") #Jan 1, 2000 #rrule = RecurrenceRule.new("FREQ=YEARLY;BYWEEKNO=20;BYDAY=MO") expected = [ DateTime.parse("US-Eastern:19970512T090000"), #May 12, 1997 DateTime.parse("US-Eastern:19980511T090000"), #May 11, 1998 DateTime.parse("US-Eastern:19990517T090000"), #May 17, 1999 ] te = (REYear.new(6) | REYear.new(7)) & REMonth.new(start_date.day) results = te.dates(DateRange.new(start_date, end_date), 10) assert_equal(expected, results) end =end # "Every Thursday in March, forever" def test_example_26 start_date = DateTime.parse("US-Eastern:19970313T090000") #Mar 13, 1997 end_date = DateTime.parse("US-Eastern:20000101T090000") #Jan 1, 2000 #rrule = RecurrenceRule.new("FREQ=YEARLY;BYMONTH=3;BYDAY=TH") expected = [ DateTime.parse("US-Eastern:19970313T090000"), #Mar 13, 1997 DateTime.parse("US-Eastern:19970320T090000"), #Mar 20, 1997 DateTime.parse("US-Eastern:19970327T090000"), #Mar 27, 1997 DateTime.parse("US-Eastern:19980305T090000"), #Mar 5, 1998 DateTime.parse("US-Eastern:19980312T090000"), #Mar 12, 1998 DateTime.parse("US-Eastern:19980319T090000"), #Mar 19, 1998 DateTime.parse("US-Eastern:19980326T090000"), #Mar 26, 1998 DateTime.parse("US-Eastern:19990304T090000"), #Mar 4, 1999 DateTime.parse("US-Eastern:19990311T090000"), #Mar 11, 1999 DateTime.parse("US-Eastern:19990318T090000"), #Mar 18, 1999 DateTime.parse("US-Eastern:19990325T090000"), #Mar 25, 1999 ] te = REYear.new(3) & DIWeek.new(Thursday) results = te.dates(DateRange.new(start_date, end_date)) assert_equal(expected, results) end # "Every Thursday, but only during June, July, and August, forever" def test_example_27 start_date = DateTime.parse("US-Eastern:19970605T090000") #Jun 5, 1997 end_date = DateTime.parse("US-Eastern:20000101T090000") #Jan 1, 2000 #rrule = RecurrenceRule.new("FREQ=YEARLY;BYDAY=TH;BYMONTH=6,7,8") expected = [ DateTime.parse("US-Eastern:19970605T090000"), #Jun 5, 1997 DateTime.parse("US-Eastern:19970612T090000"), #Jun 12, 1997 DateTime.parse("US-Eastern:19970619T090000"), #Jun 19, 1997 DateTime.parse("US-Eastern:19970626T090000"), #Jun 26, 1997 DateTime.parse("US-Eastern:19970703T090000"), #Jul 3, 1997 DateTime.parse("US-Eastern:19970710T090000"), #Jul 10, 1997 DateTime.parse("US-Eastern:19970717T090000"), #Jul 17, 1997 DateTime.parse("US-Eastern:19970724T090000"), #Jul 24, 1997 DateTime.parse("US-Eastern:19970731T090000"), #Jul 31, 1997 DateTime.parse("US-Eastern:19970807T090000"), #Aug 7, 1997 DateTime.parse("US-Eastern:19970814T090000"), #Aug 14, 1997 DateTime.parse("US-Eastern:19970821T090000"), #Aug 21, 1997 DateTime.parse("US-Eastern:19970828T090000"), #Aug 28, 1997 DateTime.parse("US-Eastern:19980604T090000"), #Jun 4, 1998 DateTime.parse("US-Eastern:19980611T090000"), #Jun 11, 1998 DateTime.parse("US-Eastern:19980618T090000"), #Jun 18, 1998 DateTime.parse("US-Eastern:19980625T090000"), #Jun 25, 1998
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
true
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/reweektest.rb
test/reweektest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for REWeek class # Author:: Matthew Lipper class REWeekTest < BaseExpressionTest def test_invalid_ctor_arg assert_raises(ArgumentError,"Expected ArgumentError for invalid day of week ordinal"){ REWeek.new(10,4) } end def test_monday_thru_friday expr = REWeek.new(Mon,Fri) assert expr.include?(@date_20040116), "Expression #{expr.to_s} should include #{@date_20040116.to_s}" assert !expr.include?(@date_20040125), "Expression #{expr.to_s} should not include #{@date_20040125.to_s}" end def test_friday_thru_tuesday expr = REWeek.new(Fri,Tue) assert expr.include?(@date_20040125), "Expression #{expr.to_s} should include #{@date_20040125.to_s}" assert !expr.include?(@pdate_20071024), "Expression #{expr.to_s} should not include #{@pdate_20071024.to_s}" end def test_range_each_week_te #Friday through Tuesday expr = REWeek.new(Friday,Tuesday) assert expr.include?(@time_20070928000000), "#{expr.inspect} should include Fri 12am" assert expr.include?(@time_20070925115959), "#{expr.inspect} should include Tue 11:59pm" assert !expr.include?(@time_20070926000000),"#{expr.inspect} should not include Wed 12am" assert !expr.include?(@time_20070927065959),"#{expr.inspect} should not include Thurs 6:59am" assert !expr.include?(@time_20070927115900),"#{expr.inspect} should not include Thurs 1159am" assert expr.include?(@time_20070929110000), "#{expr.inspect} should include Sat 11am" assert expr.include?(@time_20070929000000), "#{expr.inspect} should include Sat midnight" assert expr.include?(@time_20070929235959), "#{expr.inspect} should include Saturday one minute before midnight" assert expr.include?(@time_20070930235959), "#{expr.inspect} should include Sunday one minute before midnight" end def test_to_s assert_equal 'all week', REWeek.new(Tuesday,Tuesday).to_s assert_equal 'Thursday through Saturday', REWeek.new(Thursday,Saturday).to_s end def test_dates_mixin dates = REWeek.new(Tue,Wed).dates(@pdate_20071008..@pdate_20071030) assert dates.size == 7 end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/dprecisiontest.rb
test/dprecisiontest.rb
#!/usr/bin/env ruby require 'minitest_helper' # Unit tests for DPrecision class # # Author:: Matthew Lipper class DPrecisionTest < MiniTest::Unit::TestCase include Runt def test_comparable assert(DPrecision::YEAR<DPrecision::MONTH, "DPrecision.year was not less than DPrecision.month") assert(DPrecision::MONTH<DPrecision::WEEK, "DPrecision.month was not less than DPrecision.week") assert(DPrecision::WEEK<DPrecision::DAY, "DPrecision.week was not less than DPrecision.day") assert(DPrecision::DAY<DPrecision::HOUR, "DPrecision.day was not less than DPrecision.hour") assert(DPrecision::HOUR<DPrecision::MIN, "DPrecision.hour was not less than DPrecision.min") assert(DPrecision::MIN<DPrecision::SEC, "DPrecision.min was not less than DPrecision.sec") assert(DPrecision::SEC<DPrecision::MILLI, "DPrecision.sec was not less than DPrecision.millisec") end def test_pseudo_singleton_instance assert(DPrecision::YEAR.object_id==DPrecision::YEAR.object_id, "Object Id's not equal.") assert(DPrecision::MONTH.object_id==DPrecision::MONTH.object_id, "Object Id's not equal.") assert(DPrecision::WEEK.object_id==DPrecision::WEEK.object_id, "Object Id's not equal.") assert(DPrecision::DAY.object_id==DPrecision::DAY.object_id, "Object Id's not equal.") assert(DPrecision::HOUR.object_id==DPrecision::HOUR.object_id, "Object Id's not equal.") assert(DPrecision::MIN.object_id==DPrecision::MIN.object_id, "Object Id's not equal.") assert(DPrecision::SEC.object_id==DPrecision::SEC.object_id, "Object Id's not equal.") assert(DPrecision::MILLI.object_id==DPrecision::MILLI.object_id, "Object Id's not equal.") end def test_to_precision #February 29th, 2004 no_prec_date = PDate.civil(2004,2,29) month_prec = PDate.month(2004,2,29) assert(month_prec==DPrecision.to_p(no_prec_date,DPrecision::MONTH)) #11:59:59 am, February 29th, 2004 no_prec_datetime = PDate.civil(2004,2,29,23,59,59) #puts "-->#{no_prec_datetime.date_precision}<--" assert(month_prec==DPrecision.to_p(no_prec_datetime,DPrecision::MONTH)) end def test_label assert_equal(DPrecision::YEAR.label,"YEAR") assert_equal(DPrecision::MONTH.label,"MONTH") assert_equal(DPrecision::WEEK.label,"WEEK") assert_equal(DPrecision::DAY.label,"DAY") assert_equal(DPrecision::HOUR.label,"HOUR") assert_equal(DPrecision::MIN.label,"MINUTE") assert_equal(DPrecision::SEC.label,"SECOND") assert_equal(DPrecision::MILLI.label,"MILLISECOND") end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/remonthtest.rb
test/remonthtest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for REMonth class # Author:: Matthew Lipper class REMonthTest < BaseExpressionTest def test_20th_thru_29th_of_every_month expr = REMonth.new(20,29) assert expr.include?(@date_20050123), "Expression #{expr.to_s} should include #{@date_20050123.to_s}" assert !expr.include?(@date_20050116), "Expression #{expr.to_s} should not include #{@date_20050116.to_s}" end def test_16th_of_every_month expr = REMonth.new(16) assert expr.include?(@date_20050116), "Expression #{expr.to_s} should include #{@date_20050116.to_s}" assert !expr.include?(@date_20050123), "Expression #{expr.to_s} should not include #{@date_20050123.to_s}" end def test_dates_mixin expr = REMonth.new(22, 26) dates = expr.dates(@pdate_20071024..@pdate_20071028) assert dates.size == 3, "Expected 2 dates and got #{dates.size}" # Use default Test::Unit assertion message assert_equal "2007-10-24T00:00:00+00:00", dates[0].to_s assert_equal "2007-10-25T00:00:00+00:00", dates[1].to_s assert_equal "2007-10-26T00:00:00+00:00", dates[2].to_s end def test_range_each_month_to_s assert_equal 'from the 2nd to the 5th monthly',REMonth.new(2,5).to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/dimonthtest.rb
test/dimonthtest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for DIMonth class # Author:: Matthew Lipper class DIMonthTest < BaseExpressionTest def setup super @date_range = @date_20050101..@date_20051231 end ### # Dates functionality & tests contributed by Emmett Shear ### def test_dates_mixin_first_tuesday dates = DIMonth.new(First, Tuesday).dates(@date_range) assert dates.size == 12 dates.each do |d| assert @date_range.include?(d) assert d.wday == 2 # tuesday assert d.day < 8 # in the first week end end def test_dates_mixin_last_friday dates = DIMonth.new(Last, Friday).dates(@date_range) assert dates.size == 12 month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] dates.each do |d| assert @date_range.include?(d) assert d.wday == 5 # friday assert d.day > month_days[d.month-1] - 8 # last week end end def test_third_friday_of_the_month expr = DIMonth.new(Third,Friday) assert expr.include?(@date_20040116), "Third Friday of the month should include #{@date_20040116.to_s}" assert !expr.include?(@date_20040109), "Third Friday of the month should not include #{@date_20040109.to_s}" end def test_second_friday_of_the_month expr = DIMonth.new(Second,Friday) assert expr.include?(@date_20040109), "Second Friday of the month should include #{@date_20040109.to_s}" assert !expr.include?(@date_20040116), "Second Friday of the month should not include #{@date_20040116.to_s}" end def test_last_sunday_of_the_month expr = DIMonth.new(Last_of,Sunday) assert expr.include?(@date_20040125), "Last Sunday of the month should include #{@date_20040125}" end def test_to_s assert_equal 'last Sunday of the month', DIMonth.new(Last_of,Sunday).to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/combinedexpressionstest.rb
test/combinedexpressionstest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for composite temporal expressions # Author:: Matthew Lipper class CombinedExpressionTest < BaseExpressionTest def test_dates_on_last_fri_or_first_tues date_range = @date_20050101..@date_20051231 expr = DIMonth.new(Last, Friday) | DIMonth.new(First, Tuesday) dates = expr.dates(date_range) assert_equal 24, dates.size, "Expected 24 dates in 2005 which were either on the last Friday or first Tuesday of the month" month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] dates.each do |d| unless (d.wday == 2 and d.day < 8) or \ (d.wday == 5 and d.day > month_days[d.month-1] - 8) # Fail assert false, d.to_s end end end def test_january_except_from_7th_to_15th date_range = @date_20050101..@date_20050131 dates = (REYear.new(1, 1, 1, 31) - REMonth.new(7, 15)).dates(date_range) assert_equal 22, dates.size, "Expected 22 dates: 1/1-1/6, 1/16-1/31" end def test_work_day # Should match for 9am to 5pm except for 12pm to 1pm expr = REDay.new(9,0,17,0) - REDay.new(12,0,13,0) assert expr.include?(@pdate_200405030906), "Expression #{expr.to_s} should include #{@pdate_200405030906.to_s}" assert !expr.include?(@pdate_1975060512), "Expression #{expr.to_s} should not include #{@pdate_1975060512.to_s}" end def test_monday_tuesday_8am_to_9am expr = REWeek.new(Mon,Fri) & REDay.new(8,0,9,0) assert expr.include?(@pdate_200405040806), "Expression #{expr.to_s} should include #{@pdate_200405040806.to_s}" assert !expr.include?(@pdate_200405010806), "Expression #{expr.to_s} should not include #{@pdate_200405010806.to_s}" assert !expr.include?(@pdate_200405030906), "Expression #{expr.to_s} should not include #{@pdate_200405030906.to_s}" end def test_midnight_to_9am_or_tuesday expr = REDay.new(0,0,9,0) | DIWeek.new(Tuesday) assert expr.include?(@pdate_20071030), "Expression #{expr.to_s} should include #{@pdate_20071030.to_s}" assert expr.include?(@pdate_2012050803), "Expression #{expr.to_s} should include #{@pdate_2012050803.to_s}" assert !expr.include?(@pdate_20071116100030), "Expression #{expr.to_s} should not include #{@pdate_20071116100030.to_s}" end def test_wednesday_thru_saturday_6_to_12am expr = REWeek.new(Wed, Sat) & REDay.new(6,0,12,00) assert !expr.include?(@time_20070926000000), "Expression #{expr.to_s} should include #{@time_20070926000000.to_s}" assert expr.include?(@time_20070927065959), "Expression #{expr.to_s} should include #{@time_20070927065959.to_s}" assert !expr.include?(@time_20070928000000), "Expression #{expr.to_s} should include #{@time_20070928000000.to_s}" assert expr.include?(@time_20070929110000), "Expression #{expr.to_s} should include #{@time_20070929110000.to_s}" end def test_memorial_day # Monday through Friday, from 9am to 5pm job = REWeek.new(Mon,Fri) & REDay.new(9,00,17,00) # Memorial Day (U.S.) memorial_day = REYear.new(5) & DIMonth.new(Last,Monday) # May 29th, 2006 last_monday_in_may = @pdate_200605291012 # Before assert job.include?(last_monday_in_may), "Expression #{job.to_s} should include #{last_monday_in_may.to_s}" assert job.include?(@pdate_200605301400), "Expression #{job.to_s} should include #{@pdate_200605301400.to_s}" # Add Diff expression job_with_holiday = job - last_monday_in_may assert !job_with_holiday.include?(last_monday_in_may), "Expression #{job_with_holiday.to_s} should not include #{last_monday_in_may.to_s}" # Still have to work on Tuesday assert job.include?(@pdate_200605301400), "Expression #{job.to_s} should include #{@pdate_200605301400.to_s}" end def test_summertime #This is a hack..... #In the U.S., Memorial Day begins the last Monday of May # #The month of May may=REYear.new(5) #Monday through Saturday monday_to_saturday = REWeek.new(1,6) #Last week of (any) month last_week_in = WIMonth.new(Last_of) #So, to say 'starting from the last Monday in May', #we need to select just that last week of May begining with #the Monday of that week last_week_of_may = may & monday_to_saturday & last_week_in #This is another hack similar to the above, except instead of selecting a range #starting at the begining of the month, we need to select only the time period in #September up until Labor Day. # #In the U.S., Labor Day is the first Monday in September # #The month of September september=REYear.new(9) #First week of (any) month first_week_in = WIMonth.new(First) entire_first_week_of_september = september & first_week_in #To exclude everything in the first week which occurs on or after Monday. first_week_of_september=entire_first_week_of_september - monday_to_saturday #June through August june_through_august=REYear.new(6, 1, 8) assert june_through_august.include?(@pdate_20040704), "Expression #{june_through_august.to_s} should include #{@pdate_20040704.to_s}" #Finally! summer_time = last_week_of_may | first_week_of_september | june_through_august #Will work, but will be incredibly slow: # assert(summer_time.include?(PDate.min(2004,5,31,0,0))) assert summer_time.include?(@pdate_20040531), "Expression #{summer_time.to_s} should include #{@pdate_20040704.to_s}" assert summer_time.include?(@pdate_20040704), "Expression #{summer_time.to_s} should include #{@pdate_20040704.to_s}" #also works...also slow: # assert(!summer_time.include?(PDate.min(2004,9,6,0,0))) assert !summer_time.include?(@pdate_2004090600), "Expression #{summer_time.to_s} should not include #{@pdate_2004090600.to_s}" end def test_nyc_parking_te #Monday, Wednesday, Friday mon_wed_fri = DIWeek.new(Mon) | \ DIWeek.new(Wed) | \ DIWeek.new(Fri) assert mon_wed_fri.include?(@datetime_200403101915), "Expression #{mon_wed_fri.to_s} should include #{@datetime_200403101915.to_s}" assert !mon_wed_fri.include?(@datetime_200403140900), "Expression #{mon_wed_fri.to_s} should not include #{@datetime_200403140900.to_s}" # 8am to 11am eight_to_eleven = REDay.new(8,00,11,00) # => Mon,Wed,Fri - 8am to 11am expr1 = mon_wed_fri & eight_to_eleven # Tuesdays, Thursdays tues_thurs = DIWeek.new(Tue) | DIWeek.new(Thu) # 11:30am to 2pm eleven_thirty_to_two = REDay.new(11,30,14,00) assert eleven_thirty_to_two.include?(@datetime_200403081200), "Expression #{eleven_thirty_to_two.to_s} should include #{@datetime_200403081200.to_s}" assert !eleven_thirty_to_two.include?(@datetime_200403110000), "Expression #{eleven_thirty_to_two.to_s} should not include #{@datetime_200403110000.to_s}" # => Tues,Thurs - 11:30am to 2pm expr2 = tues_thurs & eleven_thirty_to_two # # No parking: Mon Wed Fri, 8am - 11am # Tu Thu, 11:30am - 2pm parking_ticket = expr1 | expr2 assert parking_ticket.include?(@datetime_200403111215), "Expression #{parking_ticket.to_s} should include #{@datetime_200403111215.to_s}" assert parking_ticket.include?(@datetime_200403100915), "Expression #{parking_ticket.to_s} should include #{@datetime_200403100915.to_s}" assert parking_ticket.include?(@datetime_200403100800), "Expression #{parking_ticket.to_s} should include #{@datetime_200403100800.to_s}" assert !parking_ticket.include?(@datetime_200403110115), "Expression #{parking_ticket.to_s} should not include #{@datetime_200403110115.to_s}" # The preceeding example can be condensed to: # e1 = (DIWeek.new(Mon) | DIWeek.new(Wed) | DIWeek.new(Fri)) & REDay.new(8,00,11,00) # e2 = (DIWeek.new(Tue) | DIWeek.new(Thu)) & REDay.new(11,30,14,00) # ticket = e1 | e2 end def test_dates_every_four_hours_on_tuesdays # 3am, Tuesday, May 8th, 2012 to 3am Wednesday, May 9th, 2012 range = DateRange.new(@pdate_2012050803, PDate.new(2012,5,9,15)) every_four_hours = EveryTE.new(@pdate_2012050803,4) tuesday = DIWeek.new(Tuesday) every_four_hours_on_tuesday = every_four_hours & tuesday result = every_four_hours_on_tuesday.dates(range) end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/reyeartest.rb
test/reyeartest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for REYear class # Author:: Matthew Lipper class REYearTest < BaseExpressionTest def test_ctor_one_arg expr = REYear.new(11) assert expr.start_month == 11, "Start month should equal 11" assert expr.end_month == 11, "End month should equal 11" assert expr.start_day == REYear::NO_DAY, "Start day should equal constant NO_DAY" assert expr.end_day == REYear::NO_DAY, "End day should equal constant NO_DAY" end def test_ctor_two_args expr = REYear.new(11,12) assert expr.start_month == 11, "Start month should equal 11" assert expr.end_month == 12, "End month should equal 12" assert expr.start_day == REYear::NO_DAY, "Start day should equal constant NO_DAY" assert expr.end_day == REYear::NO_DAY, "End day should equal constant NO_DAY" end def test_ctor_three_args expr = REYear.new(10,21,12) assert expr.start_month == 10, "Start month should equal 10" assert expr.end_month == 12, "End month should equal 12" assert expr.start_day == 21, "Start day should equal 21" assert expr.end_day == REYear::NO_DAY, "End day should equal constant NO_DAY" end def test_ctor_four_args expr = REYear.new(10,21,12,3) assert expr.start_month == 10, "Start month should equal 10" assert expr.end_month == 12, "End month should equal 12" assert expr.start_day == 21, "Start day should equal 21" assert expr.end_day == 3, "End day should equal 3" end def test_specific_days_same_month expr = REYear.new(10,20,10,29) assert expr.include?(@pdate_20071028), "#{expr.to_s} should include #{@pdate_20071028}" assert !expr.include?(@pdate_20071114), "#{expr.to_s} should not include #{@pdate_20071114}" assert !expr.include?(@pdate_20071030), "#{expr.to_s} should not include #{@pdate_20071030}" assert !expr.include?(@pdate_20071008), "#{expr.to_s} should not include #{@pdate_20071008}" assert !expr.include?(@pdate_20060921), "#{expr.to_s} should not include #{@pdate_20060921}" end def test_specific_days_different_months expr = REYear.new(5,31,9,6) assert expr.include?(@pdate_198606), "#{expr.to_s} should include #{@pdate_198606}" assert expr.include?(@date_20040806), "#{expr.to_s} should include #{@date_20040806}" assert !expr.include?(@pdate_20071008), "#{expr.to_s} should not include #{@pdate_20071008}" end def test_default_days_different_months expr = REYear.new(11,12) assert expr.include?(@date_19611101), "#{expr.to_s} should include #{@date_19611101}" assert !expr.include?(@pdate_198606), "#{expr.to_s} should not include #{@pdate_198606}" end def test_all_defaults expr = REYear.new(8) assert expr.include?(@date_20040806), "#{expr.to_s} should include #{@date_20040806}" assert !expr.include?(@pdate_198606), "#{expr.to_s} should not include #{@pdate_198606}" assert !expr.include?(@date_19611101), "#{expr.to_s} should not include #{@date_19611101}" end def test_same_days_same_month # Bug #5741 expr = REYear.new(9,21,9,21) assert expr.include?(@pdate_20060921), "#{expr.to_s} should include #{@pdate_20060921.to_s}" assert !expr.include?(@pdate_20060914), "#{expr.to_s} should not include #{@pdate_20060914.to_s}" end def test_to_s assert_equal 'June 1st through July 2nd', REYear.new(6, 1, 7, 2).to_s end def test_dates_mixin expr = REYear.new(4, 28, 5, 6) assert((expr.dates(@date_20040501..@date_20060504)).size == 22, "Should be 22 occurences in dates Array") end # From bug #5749 def test_mixed_precision_combo # 10:00 am to 10:01 am ten_ish = REDay.new(10,0,10,1) # September 21st every year every_21_sept = REYear.new(9,21,9,21) # Between 10:00 am and 10:01 am every September 21st combo = ten_ish & every_21_sept assert combo.include?(@pdate_20060921), "Should include lower precision argument" assert combo.include?(@pdate_200609211001), "Should include matching precision argument which is in range" assert !combo.include?(@pdate_200609211002), "Should not include matching precision argument which is out of range" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/yeartetest.rb
test/yeartetest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for YearTE class # Author:: Matthew Lipper class YearTETest < BaseExpressionTest def test_2006 expr = YearTE.new(2006) assert expr.include?(@pdate_20060914), "Expression #{expr.to_s} should include #{@pdate_20060914}" assert !expr.include?(@pdate_20071008), "Expression #{expr.to_s} should include #{@pdate_20071008}" assert expr.include?(@date_20060504), "Expression #{expr.to_s} should include #{@date_20060504}" assert !expr.include?(@date_20051231), "Expression #{expr.to_s} should include #{@date_20051231}" end def test_to_s assert_equal 'during the year 1934', YearTE.new(1934).to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/daterangetest.rb
test/daterangetest.rb
#!/usr/bin/env ruby require 'minitest_helper' # Unit tests for DateRange class # # Author:: Matthew Lipper class DateRangeTest < MiniTest::Unit::TestCase include Runt def test_sub_range r_start = PDate.min(2004,2,29,16,24) r_end = PDate.min(2004,3,2,4,22) range = DateRange.new(r_start,r_end) assert(range.min==r_start) assert(range.max==r_end) assert(range.include?(r_start+1)) assert(range.include?(r_end-1)) sub_range = DateRange.new((r_start+1),(r_end-1)) assert(range.include?(sub_range)) end def test_date r_start = PDate.min(1979,12,31,23,57) r_end = PDate.min(1980,1,1,0,2) range = DateRange.new(r_start,r_end) assert(range.min==r_start) assert(range.max==r_end) assert(range.include?(r_start+1)) assert(range.include?(r_end-1)) sub_range = DateRange.new((r_start+1),(r_end-1)) assert(range.include?(sub_range)) end def test_spaceship_operator r_start = PDate.min(1984,8,31,22,00) r_end = PDate.min(1984,9,15,0,2) range = DateRange.new(r_start,r_end) assert(-1==(range<=>(DateRange.new(r_start+2,r_end+5)))) assert(1==(range<=>(DateRange.new(r_start-24,r_end+5)))) assert(0==(range<=>(DateRange.new(r_start,r_end)))) end def test_overlap r_start = PDate.month(2010,12) r_end = PDate.month(2011,12) range = DateRange.new(r_start,r_end) o_start = PDate.month(2010,11) o_end = PDate.month(2012,2) o_range = DateRange.new(o_start,o_end) assert(range.overlap?(o_range)) assert(o_range.overlap?(range)) assert(o_range.overlap?(DateRange.new(r_start,o_end))) assert(o_range.overlap?(DateRange.new(o_start,r_end))) # September 18th - 19th, 2005, 8am - 10am expr1=DateRange.new(PDate.day(2005,9,18),PDate.day(2005,9,19)) # September 19th - 20th, 2005, 9am - 11am expr2=DateRange.new(PDate.day(2005,9,19),PDate.day(2005,9,20)) assert(expr1.overlap?(expr2)) end def test_empty r_start = PDate.hour(2004,2,10,0) r_end = PDate.hour(2004,2,9,23) empty_range = DateRange.new(r_start,r_end) assert(empty_range.empty?) assert(DateRange::EMPTY.empty?) # start == end should be empty assert DateRange.new(r_start,r_start).empty?, "Range should be empty when start == end" end def test_gap r_start = PDate.day(2000,6,12) r_end = PDate.day(2000,6,14) range = DateRange.new(r_start,r_end) g_start = PDate.day(2000,6,18) g_end = PDate.day(2000,6,20) g_range = DateRange.new(g_start,g_end) the_gap=range.gap(g_range) assert(the_gap.start_expr==(r_end+1)) assert(the_gap.end_expr==(g_start-1)) end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/collectiontest.rb
test/collectiontest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for Collection class # Author:: Matthew Lipper class CollectionTest < BaseExpressionTest def setup super @expr = Collection.new end def test_initialize assert !@expr.expressions.nil?, "Newly created Collection should have a non-nil @expressions attribute" assert @expr.expressions.empty?, "Newly created Collection should have an empty @expressions attribute" end def test_include #base class that should always return false assert !@expr.include?(StubExpression.new(true)), "Collection#include? should always return false" end def test_to_s assert_equal 'empty', @expr.to_s assert_equal 'empty', @expr.to_s{['b','oo']} dim = StubExpression.new(false,"Mock1") @expr.expressions << dim assert_equal 'ff' + dim.to_s, @expr.to_s{['ff','nn']} red = StubExpression.new(false, "Mock2") @expr.expressions << red assert_equal 'ff' + dim.to_s + 'nn' + red.to_s, @expr.to_s{['ff','nn']} wim = StubExpression.new(false, "Mock3") @expr.expressions << wim assert_equal 'ff' + dim.to_s + 'nn' + red.to_s + 'nn' + wim.to_s, @expr.to_s{['ff','nn']} end def test_add e1 = StubExpression.new e2 = StubExpression.new assert @expr.expressions.empty?, "Empty Collection should not include any expressions" result = @expr.add(e1) assert_same @expr, result, "Collection#add method should return self instance" assert @expr.expressions.include?(e1), "Collection should include added expression" @expr.add(e2) assert @expr.expressions.include?(e2), "Collection should include added expression" assert_same e2, @expr.expressions.pop, "Collection should keep added expressions in stack order" assert_same e1, @expr.expressions.pop, "Collection should keep added expressions in stack order" end def test_overlap stub = StubExpression.new(false, "stubby", true) # start with "always overlap?" stub assert !@expr.overlap?(stub), "Empty Collection should never overlap" @expr.add StubExpression.new assert @expr.overlap?(stub), "Collection should overlap with given stub argument" assert_same stub.args[0], @expr.expressions.first, "First expression should be given to stub in the first call to overlap?" stub.overlap = false assert !@expr.overlap?(stub), "Collection should not overlap with given stub argument" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/weekintervaltest.rb
test/weekintervaltest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' class WeekIntervalTest < BaseExpressionTest def test_every_other_week expr = WeekInterval.new(Date.new(2013,4,23),2) good_dates = [Date.new(2013,4,21), Date.new(2013,4,27),Date.new(2013,5,8)] good_dates.each do |date| assert(expr.include?(date),"Expr<#{expr}> should include #{date.ctime}") end bad_dates = [Date.new(2013,4,20), Date.new(2013,4,28)] bad_dates.each do |date| assert(!expr.include?(date),"Expr<#{expr}> should not include #{date.ctime}") end end def test_every_third_week_spans_a_year expr = WeekInterval.new(Date.new(2013,12,25),3) good_dates = [Date.new(2013,12,22),Date.new(2014,1,12)] good_dates.each do |date| assert(expr.include?(date),"Expr<#{expr}> should include #{date.ctime}") end bad_dates = [Date.new(2013,12,21), Date.new(2013,12,31),Date.new(2014,01,11),Date.new(2014,01,19)] bad_dates.each do |date| assert(!expr.include?(date),"Expr<#{expr}> should not include #{date.ctime}") end end def test_biweekly_with_sunday_start_with_diweek every_other_friday = WeekInterval.new(Date.new(2006,2,26), 2) & DIWeek.new(Friday) # should match the First friday and every other Friday after that good_dates = [Date.new(2006,3,3), Date.new(2006,3,17), Date.new(2006,3,31)] bad_dates = [Date.new(2006,3,1), Date.new(2006,3,10), Date.new(2006,3,24)] good_dates.each do |date| assert every_other_friday.include?(date), "Expression #{every_other_friday.to_s} should include #{date}" end bad_dates.each do |date| assert !every_other_friday.include?(date), "Expression #{every_other_friday.to_s} should not include #{date}" end end def test_biweekly_with_friday_start_with_diweek every_other_wednesday = WeekInterval.new(Date.new(2006,3,3), 2) & DIWeek.new(Wednesday) # should match the First friday and every other Friday after that good_dates = [Date.new(2006,3,1), Date.new(2006,3,15), Date.new(2006,3,29)] bad_dates = [Date.new(2006,3,2), Date.new(2006,3,8), Date.new(2006,3,22)] good_dates.each do |date| assert every_other_wednesday.include?(date), "Expression #{every_other_wednesday.to_s} should include #{date}" end bad_dates.each do |date| assert !every_other_wednesday.include?(date), "Expression #{every_other_wednesday.to_s} should not include #{date}" end end def test_tue_thur_every_third_week_with_diweek every_tth_every_3 = WeekInterval.new(Date.new(2006,5,1), 3) & (DIWeek.new(Tuesday) | DIWeek.new(Thursday)) # should match the First tuesday and thursday for week 1 and every 3 weeks thereafter good_dates = [Date.new(2006,5,2), Date.new(2006,5,4), Date.new(2006,5,23), Date.new(2006,5,25), Date.new(2006,6,13), Date.new(2006,6,15)] bad_dates = [Date.new(2006,5,3), Date.new(2006,5,9), Date.new(2006,5,18)] good_dates.each do |date| assert every_tth_every_3.include?(date), "Expression #{every_tth_every_3.to_s} should include #{date}" end bad_dates.each do |date| assert !every_tth_every_3.include?(date), "Expression #{every_tth_every_3.to_s} should not include #{date}" end range_start = Date.new(2006,5,1) range_end = Date.new(2006,8,1) expected_dates = [ Date.new(2006,5,2), Date.new(2006,5,4), Date.new(2006,5,23), Date.new(2006,5,25), Date.new(2006,6,13), Date.new(2006,6,15), Date.new(2006,7,4), Date.new(2006,7,6), Date.new(2006,7,25), Date.new(2006,7,27) ] dates = every_tth_every_3.dates(DateRange.new(range_start, range_end)) assert_equal dates, expected_dates end def test_to_s date = Date.new(2006,2,26) assert_equal "every 2nd week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 2).to_s assert_equal "every 3rd week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 3).to_s assert_equal "every 4th week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 4).to_s assert_equal "every 5th week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 5).to_s assert_equal "every 6th week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 6).to_s assert_equal "every 7th week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 7).to_s assert_equal "every 8th week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 8).to_s assert_equal "every 9th week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 9).to_s assert_equal "every 10th week starting with the week containing #{Runt.format_date(date)}", WeekInterval.new(date, 10).to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/baseexpressiontest.rb
test/baseexpressiontest.rb
#!/usr/bin/env ruby require 'minitest_helper.rb' $DEBUG=false # Base test case for refactored temporal expression unit tests # Author:: Matthew Lipper class BaseExpressionTest < MiniTest::Unit::TestCase include Runt include DPrecision def setup @stub1 = StubExpression.new(false, "stub 1", false) @stub2 = StubExpression.new(false, "stub 2", false) @pdate_198606 = PDate.month(1986,6) # June, 1986 @pdate_20040531 = PDate.day(2004,5,31) # Monday, May 31st, 2004 @pdate_20040704 = PDate.day(2004,7,4) # Sunday, July 4th, 2004 @pdate_20060914 = PDate.day(2006,9,14) # Thursday, September 14th, 2006 @pdate_20060921 = PDate.day(2006,9,21) # Thursday, September 21st, 2006 @pdate_20071008 = PDate.day(2007,10,8) # Monday, October 8th, 2007 @pdate_20071024 = PDate.day(2007,10,24) # Wednesday, October 24th, 2007 @pdate_20071028 = PDate.day(2007,10,28) # Sunday, October 28th, 2007 @pdate_20071030 = PDate.day(2007,10,30) # Tuesday, October 30th, 2007 @pdate_20071114 = PDate.day(2007,11,14) # Wednesday, November 14th, 2007 @pdate_20081112 = PDate.day(2008,11,12) # Wednesday, November 12th, 2008 @pdate_1922041816 = PDate.hour(1922,4,18,16) # 4pm, Tuesday, April 18th, 1922 @pdate_1975060512 = PDate.hour(1975,6,5,12) # 12pm, Thursday, June 5th, 1975 @pdate_2004090600 = PDate.hour(2004,9,6,0) # 12am, Monday, September 6th, 2004 @pdate_2012050803 = PDate.hour(2012,5,8,3) # 3am, Tuesday, May 8th, 2012 @pdate_2012050815 = PDate.hour(2012,5,8,15) # 3pm, Tuesday, May 8th, 2012 @pdate_200401282100 = PDate.min(2004,1,28,21,0) # 9:00pm, Wednesday, January 28th, 2004 @pdate_200401280000 = PDate.min(2004,1,28,0,0) # 12:00am, Wednesday, January 28th, 2004 @pdate_200401280001 = PDate.min(2004,1,28,0,1) # 12:01am, Wednesday, January 28th, 2004 @pdate_200405010806 = PDate.min(2004,5,1,8,6) # 8:06am, Saturday, May 1st, 2004 @pdate_200405030906 = PDate.min(2004,5,3,9,6) # 9:06am, Monday, May 3rd, 2004 @pdate_200405040806 = PDate.min(2004,5,4,8,6) # 8:06am, Tuesday, May 4th, 2004 @pdate_200605291012 = PDate.min(2006,5,29,10,12) @pdate_200605301400 = PDate.min(2006,5,30,14,00) @pdate_200609211001 = PDate.min(2006,9,21,10,1) @pdate_200609211002 = PDate.min(2006,9,21,10,2) @pdate_20071116100030 = PDate.sec(2007,11,16,10,0,30) @date_19611101 = Date.civil(1961,11,1) @date_20040109 = Date.civil(2004,1,9) # Friday, January 9th 2004 @date_20040116 = Date.civil(2004,1,16) # Friday, January 16th 2004 @date_20040125 = Date.civil(2004,1,25) # Sunday, January 25th 2004 @date_20040501 = Date.civil(2004,5,1) @date_20040806 = Date.civil(2004,8,6) @date_20050101 = Date.civil(2005,1,1) @date_20050102 = Date.civil(2005,1,2) @date_20050109 = Date.civil(2005,1,9) @date_20050116 = Date.civil(2005,1,16) @date_20050123 = Date.civil(2005,1,23) @date_20050130 = Date.civil(2005,1,30) @date_20050131 = Date.civil(2005,1,31) @date_20050228 = Date.civil(2005,2,28) @date_20051231 = Date.civil(2005,12,31) @date_20060504 = Date.civil(2006,5,4) @datetime_200403081200 = DateTime.new(2004,3,8,12,0) # 12:00pm, Monday, March 8th, 2004 @datetime_200403100800 = DateTime.new(2004,3,10,8,00) @datetime_200403100915 = DateTime.new(2004,3,10,9,15) @datetime_200403101915 = DateTime.new(2004,3,10,19,15) # 7:15pm, Wednesday, March 10th, 2004 @datetime_200403110000 = DateTime.new(2004,3,11,0,0) # 12:00am, Thursday, March 11th, 2004 @datetime_200403110115 = DateTime.new(2004,3,11,1,15) @datetime_200403111215 = DateTime.new(2004,3,11,12,15) @datetime_200403140900 = DateTime.new(2004,3,14,9,00) # 9:00am, Sunday, March 14th, 2004 @datetime_200709161007 = DateTime.new(2007,9,16,10,7) @time_20070925115959 = Time.mktime(2007,9,25,11,59,59) # 11:59:59am, Tuesday, September 25th, 2007 @time_20070926000000 = Time.mktime(2007,9,26,0,0,0) # 12:00:00am, Wednesday, September 26th, 2007 @time_20070927065959 = Time.mktime(2007,9,27,6,59,59) # 6:59:59am, Thursday, September 27th, 2007 @time_20070927115900 = Time.mktime(2007,9,27,11,59,0) # 11:59:00am, Thursday, September 27th, 2007 @time_20070928000000 = Time.mktime(2007,9,28,0,0,0) # 12:00:00am, Friday, September 28th, 2007 @time_20070929110000 = Time.mktime(2007,9,29,11,0,0) # 11:00:00am, Saturday, September 29th, 2007 @time_20070929000000 = Time.mktime(2007,9,29,0,0,0) # 12:00:00am, Saturday, September 29th, 2007 @time_20070929235959 = Time.mktime(2007,9,29,23,59,59) # 11:59:59pm, Saturday, September 29th, 2007 @time_20070930235959 = Time.mktime(2007,9,30,23,59,59) # 11:59:59am, Sunday, September 30th, 2007 end # override default_test keeps it from growling about no other tests in this file def default_test; end def assert_raise_message(types, matcher, message = nil, &block) args = [types].flatten + [message] exception = assert_raise(*args, &block) assert_match matcher, exception.message, message end end class StubExpression include Runt include TExpr attr_accessor :match, :string, :overlap, :args def initialize(match=false, string="StubExpression",overlap=false) @match=match @string=string @overlap=overlap @args=[] end def include?(arg) @args << arg @match end def overlap?(arg) @args << arg @overlap end def to_s @string end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/difftest.rb
test/difftest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for Diff class # Author:: Matthew Lipper class DiffTest < BaseExpressionTest def setup super @diff = Diff.new(@stub1, @stub2) @date = @pdate_20071008 end def test_initialize assert_same @stub1, @diff.expr1, "Expected #{@stub1} instance used to create expression. Instead got #{@diff.expr1}" assert_same @stub2, @diff.expr2, "Expected #{@stub2} instance used to create expression. Instead got #{@diff.expr2}" end def test_to_s assert_equal @stub1.to_s + ' except for ' + @stub2.to_s, @diff.to_s end def test_include # Diff will match only if expr1 && !expr2 @stub1.match = false @stub2.match = false assert !@diff.include?(@date), "Diff instance should not include any dates" @stub2.match = true assert !@diff.include?(@date), "Diff instance should not include any dates" @stub1.match = true assert !@diff.include?(@date), "Diff instance should not include any dates" @stub2.match = false assert @diff.include?(@date), "Diff instance should include any dates" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/intersecttest.rb
test/intersecttest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for Intersect class # Author:: Matthew Lipper class IntersectTest < BaseExpressionTest def setup super @intersect = Intersect.new @date = @pdate_20071008 end def test_to_s assert_equal 'empty', @intersect.to_s @intersect.add(@stub1) assert_equal 'every ' + @stub1.to_s, @intersect.to_s @intersect.add(@stub2) assert_equal 'every ' + @stub1.to_s + ' and ' + @stub2.to_s, @intersect.to_s end def test_include assert !@intersect.include?(@date), "Empty Intersect instance should not include any dates" @intersect.add(@stub1).add(@stub2) # both expressions will return false assert !@intersect.include?(@date), "Intersect instance should not include any dates" @stub2.match = true assert !@intersect.include?(@date), "Intersect instance should not include any dates" @stub1.match = true assert @intersect.include?(@date), "Intersect instance should include any dates" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/scheduletest.rb
test/scheduletest.rb
#!/usr/bin/env ruby require 'minitest_helper' # Unit tests for Schedule classes # Author:: Matthew Lipper class ScheduleTest < MiniTest::Unit::TestCase include Runt def setup # Jane is very busy these days. @sched=Schedule.new # Elmo's World is on TV: Mon-Fri 8am-8:30am @elmo=Event.new("Elmo's World") @elmo_broadcast=(REWeek.new(Mon,Fri) & REDay.new(8,00,8,30)) @sched.add(@elmo,@elmo_broadcast) #Oobi's on TV: Thu-Sat 8:30am-9am @oobi=Event.new("Oobi") @oobi_broadcast=(REWeek.new(Thu,Sat) & REDay.new(8,30,9,00)) @sched.add(@oobi,@oobi_broadcast) @during_elmo=PDate.new(2004,5,4,8,06) @not_during_elmo=PDate.new(2004,5,1,8,06) @during_oobi=PDate.new(2004,4,30,8,56) @not_during_oobi=PDate.new(2004,5,1,8,12) end def test_include # Check Elmo assert(@sched.include?(@elmo, @during_elmo)) assert(!@sched.include?(@elmo,@not_during_elmo)) assert(!@sched.include?(@elmo,@during_oobi)) # Check Oobi assert(@sched.include?(@oobi, @during_oobi)) assert(!@sched.include?(@oobi,@not_during_oobi)) assert(!@sched.include?(@oobi,@not_during_elmo)) end def test_select_all # select all all=@sched.select {|ev,xpr| true; } assert all.size==2 assert all.include?(@elmo) assert all.include?(@oobi) end def test_select_none # select none assert((@sched.select {|ev,xpr| false; }).size==0) end def test_select_some # select oobi only some=@sched.select {|ev,xpr| @oobi.eql?(ev); } assert some.size==1 assert !some.include?(@elmo) assert some.include?(@oobi) some.clear # select elmo only some=@sched.select {|ev,xpr| @elmo.eql?(ev); } assert some.size==1 assert some.include?(@elmo) assert !some.include?(@oobi) end def test_events events=@sched.events(PDate.new(2006,12,4,11,15)) assert_equal 0,events.size # The Barney power hour which overlaps with Elmo barney=Event.new("Barney") @sched.add(barney,REDay.new(7,30,8,30)) events=@sched.events(PDate.new(2006,12,4,8,15)) assert_equal 2,events.size assert events.include?(barney) assert events.include?(@elmo) end def test_update @sched.update(Event.new("aaa")){|ev|assert_nil(ev)} @sched.update(@elmo){|ev|assert_equal(@elmo_broadcast,ev)} @sched.update(@oobi){|ev|assert_equal(@oobi_broadcast,ev)} end def test_select_old @sched=Schedule.new e1=Event.new("e1") assert(!@sched.include?(e1,nil)) #FIXME: Temporarily comment this out since it hangs JRuby 1.9 #range=TemporalRange.new(DateRange.new(PDate.new(2006,12,3),PDate.new(2007,1,24))) #in_range=PDate.new(2007,1,4) #assert(range.include?(in_range)) #out_of_range=PDate.new(2006,1,4) #assert(!range.include?(out_of_range)) #@sched.add(e1,range) #assert(@sched.include?(e1,in_range)) #assert(!@sched.include?(e1,out_of_range)) end def test_dates # range: May 1st, 2004 to May 31st, 2004 d_range = DateRange.new(PDate.day(2004,5,1), PDate.day(2004,5,31)) @sched = Schedule.new event = Event.new("Visit Ernie") # First and last Friday of the month expr1 = DIMonth.new(1,Fri) | DIMonth.new(-1,Fri) @sched.add(event,expr1) dates = @sched.dates(event,d_range) expected = [PDate.day(2004,5,7), PDate.day(2004,5,28)] assert_equal(expected,dates) end def test_using_a_schedule # September 18th - 19th, 2005, 8am - 10am expr1=TemporalRange.new(DateRange.new(PDate.day(2005,9,18),PDate.day(2005,9,19))) & REDay.new(8,0,10,0) assert(expr1.include?(PDate.min(2005,9,18,8,15))) # September 19th - 20th, 2005, 9am - 11am expr2=TemporalRange.new(DateRange.new(PDate.day(2005,9,19),PDate.day(2005,9,20))) & REDay.new(9,0,11,0) # Quick sanuty check assert(expr1.overlap?(expr2)) # Setup a @schedule w/first expression @sched = Schedule.new @sched.add(Event.new("Snafubar Opening"),expr1) resource = Resource.new(@sched) # Add a another overlapping event resource.add_event(Event.new("Yodeling Lesson"),expr2) # Create a new resource using the same schedule resource2 = Resource.new(@sched) # Add a another overlapping event and pass a block which should complain #resource.add_event(Event.new("Yodeling Lesson"),expr2) \ #{|e,s| raise "Resource not available at requested time(s)." \ # if (@schedule.overlap?(s))} end end class Resource def initialize(schedule) @schedule=schedule end def add_event(event,expr) if(block_given?) yield(event,expr) else @schedule.add(event,expr) end end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/uniontest.rb
test/uniontest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for Union class # Author:: Matthew Lipper class UnionTest < BaseExpressionTest def setup super @union = Union.new @date = @pdate_20071028 end def test_include assert !@union.include?(@date), "Empty Union instance should not include any dates" @union.add(@stub1).add(@stub2) # both expressions will return false assert !@union.include?(@date), "Union instance should not include any dates" @stub2.match = true assert @union.include?(@date), "Union instance should include any dates" @stub2.match = false @stub1.match = true assert @union.include?(@date), "Union instance should include any dates" end def test_to_s assert_equal 'empty', @union.to_s @union.add(@stub1) assert_equal 'every ' + @stub1.to_s, @union.to_s @union.add(@stub2) assert_equal 'every ' + @stub1.to_s + ' or ' + @stub2.to_s, @union.to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/runttest.rb
test/runttest.rb
#!/usr/bin/env ruby require 'minitest_helper' class RuntModuleTest < MiniTest::Unit::TestCase def test_last assert Runt::Last == -1 end def test_last_of assert Runt::Last_of == -1 end def test_second_to_last assert Runt::Second_to_last == -2 end def test_ordinals #1.upto(31){ |n| puts Runt.ordinalize(n); } assert_equal '1st', Runt.ordinalize(1) assert_equal '33rd', Runt.ordinalize(33) assert_equal '50th', Runt.ordinalize(50) assert_equal '2nd', Runt.ordinalize(2) assert_equal 'second to last', Runt.ordinalize(-2) assert_equal 'last', Runt.ordinalize(-1) end def test_day_name i=0 Date::DAYNAMES.each do |n| assert_equal Date::DAYNAMES[i], Runt.day_name(i) i=i+1 end end def test_month_name i=0 Date::MONTHNAMES.each do |n| assert_equal Date::MONTHNAMES[i], Runt.month_name(i) i=i+1 end end def test_strftime d=DateTime.new(2006,2,26,14,45) assert_equal '02:45PM', Runt.format_time(d) end def test_numeric_class_additions assert_equal 0.000001, 1.microsecond assert_equal 0.000001, 1.microseconds assert_equal 0.001, 1.millisecond assert_equal 0.001, 1.milliseconds assert_equal 7, 7.second assert_equal 7, 7.seconds assert_equal 60, 1.minute assert_equal 60, 1.minutes assert_equal 3600, 1.hour assert_equal 3600, 1.hours assert_equal 86400, 1.day assert_equal 86400, 1.days assert_equal 604800, 1.week assert_equal 604800, 1.weeks assert_equal 2592000, 1.month assert_equal 2592000, 1.months assert_equal 31536000, 1.year assert_equal 31536000, 1.years assert_equal 315360000, 1.decade assert_equal 315360000, 1.decades end def test_time_class_dprecision time=Time.parse('Monday 06 November 2006 07:38') assert_equal(Runt::DPrecision::DEFAULT,time.date_precision) end def test_date_class_dprecision date=Date.today assert_equal(Runt::DPrecision::DAY,date.date_precision) end def test_datetime_class_dprecision date=DateTime.civil assert_equal(Runt::DPrecision::SEC,date.date_precision) end def test_time_plus time=Time.local(2006, 12, 9, 5, 56, 12) # Default precision is minute assert_equal(Runt::PDate.min(2006,12,9,5,56),Runt::DPrecision.to_p(time)) refute_equal(Time.parse("Sat Dec 09 05:56:00 -0500 2006"),time) end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/aftertetest.rb
test/aftertetest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for AfterTE class # Author:: Matthew Lipper class AfterTETest < BaseExpressionTest include TExpr def test_include_inclusive expr = AfterTE.new(@pdate_20071030, true) assert !expr.include?(@date_20050101), "Should not include an earlier date" assert expr.include?(@pdate_20071114), "Should include a later date" assert expr.include?(@pdate_20071030), "Should include the same date" end def test_include_non_inclusive expr = AfterTE.new(@pdate_20071030) assert !expr.include?(@date_20050101), "Should not include an earlier date" assert expr.include?(@pdate_20071114), "Should include a later date" assert !expr.include?(@pdate_20071030), "Should not include the same date" end def test_to_s expr = AfterTE.new(@pdate_20071114) assert_equal "after #{Runt.format_date(@pdate_20071114)}", expr.to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/expressionbuildertest.rb
test/expressionbuildertest.rb
#!/usr/bin/env ruby require 'minitest_helper' class ExpressionBuilderTest < MiniTest::Unit::TestCase def setup @builder = ExpressionBuilder.new end def test_define_should_instance_eval_a_block @builder.define do @ctx = "meow" end assert_equal "meow", @builder.ctx, "Expected instance variable @ctx to be set by block" end def test_add_should_initialize_empty_ctx_with_expression result = @builder.add('expr',:to_s) assert_equal 'expr', result, "Result should equal string given to add method" assert_equal 'expr', @builder.ctx, "Builder context should equal result" end def test_add_should_send_op_to_ctx_with_expression @builder.add('abc',:to_s) result = @builder.add('def',:concat) assert_equal 'abcdef', result, "Result should equal concatenated strings given to add method" assert_equal 'abcdef', @builder.ctx, "Builder context should equal result" end def test_on_should_call_add_with_expression_and_ampersand @builder.add(1,:to_s) result = @builder.on(3) # result = 1 & 3 assert_equal 1, result, "Result should equal 1 == 1 & 3" assert_equal 1, @builder.ctx, "Builder context should equal result" end def test_except_should_call_add_with_expression_and_minus @builder.add(1,:to_s) result = @builder.except(3) # result = 1 - 3 assert_equal -2, result, "Result should equal -2 == 1 - 3" assert_equal -2, @builder.ctx, "Builder context should equal result" end def test_possibly_should_call_add_with_expression_and_pipe @builder.add(1, :to_s) result = @builder.possibly(2) # result = 1 | 2 assert_equal 3, result, "Result should equal 3 == 1 | 2" assert_equal 3, @builder.ctx, "Builder context should equal result" end def test_builder_created_expression_should_equal_manually_created_expression manual = Runt::REDay.new(8,45,9,30) & Runt::DIWeek.new(Runt::Friday) | \ Runt::DIWeek.new(Runt::Saturday) - Runt::DIMonth.new(Runt::Last, Runt::Friday) expression = @builder.define do on daily_8_45am_to_9_30am on friday possibly saturday except last_friday end assert_equal manual.to_s, expression.to_s, "Expected #{manual.to_s} but was #{expression.to_s}" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/dayintervaltetest.rb
test/dayintervaltetest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for DayIntervalTE class # Author:: Matthew Lipper class DayIntervalTETest < BaseExpressionTest def test_every_8_days date = @date_20040116 # Match every 8 days expr = DayIntervalTE.new(date, 8) assert expr.include?(date + 8), "Expression #{expr.to_s} should include #{(date + 8).to_s}" assert expr.include?(date + 16), "Expression #{expr.to_s} should include #{(date + 16).to_s}" assert expr.include?(date + 64), "Expression #{expr.to_s} should include #{(date + 64).to_s}" assert !expr.include?(date + 4), "Expression #{expr.to_s} should not include #{(date + 4).to_s}" # FIXME This test fails #assert !expr.include?(date - 8), "Expression #{expr.to_s} should not include #{(date - 8).to_s}" end def test_every_2_days date = @datetime_200709161007 expr = DayIntervalTE.new(date, 2) assert expr.include?(date + 2), "Expression #{expr.to_s} should include #{(date + 2).to_s}" assert expr.include?(date + 4), "Expression #{expr.to_s} should include #{(date + 4).to_s}" assert !expr.include?(date + 3), "Expression #{expr.to_s} should not include #{(date + 3).to_s}" end def test_to_s every_four_days = DayIntervalTE.new(Date.new(2006,2,26), 4) assert_equal "every 4th day after #{Runt.format_date(Date.new(2006,2,26))}", every_four_days.to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/wimonthtest.rb
test/wimonthtest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for WIMonth class # Author:: Matthew Lipper class WIMonthTest < BaseExpressionTest def setup super @date_range = @date_20050101..@date_20050228 end def test_second_week_in_month expr = WIMonth.new(Second) assert expr.include?(@pdate_20071008), "#{expr.to_s} should include #{@pdate_20071008.to_s}" assert !expr.include?(@pdate_20071030), "#{expr.to_s} should not include #{@pdate_20071030.to_s}" end def test_last_week_in_month expr = WIMonth.new(Last_of) # Make sure of day precision or things will be unusably slow! assert expr.include?(@pdate_20071030), "#{expr.to_s} should include #{@pdate_20071030.to_s}" assert !expr.include?(@pdate_20071008), "#{expr.to_s} should not include #{@pdate_20071008.to_s}" end def test_second_to_last_week_in_month expr = WIMonth.new(Second_to_last) # Make sure of day precision or things will be unusably slow! assert expr.include?(@pdate_20071024), "#{expr.to_s} should include #{@pdate_20071024}" assert !expr.include?(@pdate_20071008), "#{expr.to_s} should not include #{@pdate_20071008}" end def test_dates_mixin_second_week_in_month dates = WIMonth.new(Second).dates(@date_range) assert dates.size == 14, "Expected 14 dates, was #{dates.size}" assert dates.first.mday == 8, "Expected first date.mday to be 8, was #{dates.first.mday}" assert dates.last.mday == 14, "Expected last date.mday to be 14, was #{dates.last.mday}" end def test_dates_mixin_last_week_in_month dates = WIMonth.new(Last).dates(@date_range) assert dates.size == 14, "Expected 14 dates, was #{dates.size}" assert dates.first.mday == 25, "Expected first date.mday to be 25, was #{dates.first.mday}" assert dates.last.mday == 28, "Expected last date.mday to be 28, was #{dates.last.mday}" end def test_week_in_month_to_s assert_equal 'last week of any month', WIMonth.new(Last).to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/temporalrangetest.rb
test/temporalrangetest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for TemporalRange class # Author:: Matthew Lipper class TemporalRangeTest < BaseExpressionTest def test_include rspec = TemporalRange.new(@stub1) assert !rspec.include?("Any Object"), "Expression should not include any given argument" @stub1.match = true assert rspec.include?("Any Object"), "Expression should include any given argument" end def test_overlap range = DateRange.new(@date_20050101, @date_20050109) rspec = TemporalRange.new(range) assert !rspec.include?(@date_20050116), "Expression #{rspec.to_s} should not include #{@date_20050116.to_s}" assert rspec.include?(@date_20050102), "Expression #{rspec.to_s} should include #{@date_20050102.to_s}" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/temporaldatetest.rb
test/temporaldatetest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for TemporalDate class # Author:: Matthew Lipper class TemporalDateTest < BaseExpressionTest def setup super @spec = TemporalDate.new(@stub1) end def test_initialize assert_same @stub1, @spec.date_expr, "Expected #{@stub1}, instead got #{@spec.date_expr}" end def test_specific_date date_spec = TemporalDate.new(Date.new(2006,06,27)) assert !date_spec.include?(Date.new(2005,06,27)) assert !date_spec.include?(Date.new(2006,06,26)) assert date_spec.include?(Date.new(2006,06,27)) assert !date_spec.include?(Date.new(2006,06,28)) assert !date_spec.include?(Date.new(2007,06,27)) end def test_include_arg_has_include_method assert !@spec.include?(@stub2), "Expression should not include configured stub" @stub2.match = true assert @spec.include?(@stub2), "Expression should include configured stub" end def test_include_arg_without_include_method @spec = TemporalDate.new(4) assert !@spec.include?(3), "Expression #{@spec.to_s} should not include 3" assert @spec.include?(4), "Expression #{@spec.to_s} should include 4" end def test_to_s assert_equal @stub1.to_s, @spec.to_s end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/temporalexpressiontest.rb
test/temporalexpressiontest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for TExpr classes # Author:: Matthew Lipper class TExprTest < BaseExpressionTest include TExpr def test_include assert !self.include?(true), "Default include? method should always return false" end def test_to_s assert_equal self.to_s, 'TExpr', "Default to_s method should always return 'TExpr'" end def test_or_from_union union = Union.new same_union = union.or(@stub1) assert_same union, same_union, "Expected same Union instance that received the or method" assert_same @stub1, union.expressions.first, "Union instance should have added the stub expression" end def test_or_from_nonunion result = @stub1.or(@stub2) {|e| e} assert_equal Runt::Union, result.class, "Expected an Union instance. Instead got #{result.class}" assert_same @stub1, result.expressions.first, "Result should be new Union instance containing both stub expressions" assert_same @stub2, result.expressions.last, "Result should be new Union instance containing both stub expressions" end def test_and_from_intersect intersect = Intersect.new result = intersect.and(@stub1) assert_same intersect, result, "Expected same Intersect instance that received the and method" assert_same @stub1, intersect.expressions.first, "Intersect instance should have added the stub expression" end def test_or_from_nonintersect result = @stub1.and(@stub2) {|e| e} assert_equal Runt::Intersect, result.class, "Expected an Intersect instance. Instead got #{result.class}" assert_same @stub1, result.expressions.first, "Result should be new Intersect instance containing both stub expressions" assert_same @stub2, result.expressions.last, "Result should be new Intersect instance containing both stub expressions" end def test_minus result = @stub1.minus(@stub2) {|e| e} assert_equal Runt::Diff, result.class, "Expected an Diff instance. Instead got #{result.class}" assert_same @stub1, result.expr1, "Expected first stub instance used to create Diff expression" assert_same @stub2, result.expr2, "Expected second stub instance used to create Diff expression" end def test_dates_no_limit # Normally, your range is made up of Date-like Objects range = 1..3 assert @stub1.dates(range).empty?, "Expected empty Array of Objects returned from stub expression" @stub1.match = true result = @stub1.dates(range) assert_equal 1, result[0], "Expected Array of Objects given by range to be returned from stub expression" assert_equal 2, result[1], "Expected Array of Objects given by range to be returned from stub expression" assert_equal 3, result[2], "Expected Array of Objects given by range to be returned from stub expression" end def test_dates_with_limit range = 1..3 assert @stub1.dates(range).empty?, "Expected empty Array of Objects returned from stub expression" @stub1.match = true result = @stub1.dates(range,2) assert_equal 2, result.size, "Expected Array of only 2 Objects. Got #{result.size}" assert_equal 1, result[0], "Expected Array of Objects given by range to be returned from stub expression" assert_equal 2, result[1], "Expected Array of Objects given by range to be returned from stub expression" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/test/redaytest.rb
test/redaytest.rb
#!/usr/bin/env ruby require 'baseexpressiontest' # Unit tests for REDay class # Author:: Matthew Lipper class REDayTest < BaseExpressionTest def test_noon_to_430 #noon to 4:30pm expr = REDay.new(12,0,16,30) assert expr.include?(@pdate_2012050815), "Expression #{expr.to_s} should include #{@pdate_2012050815.to_s}" assert expr.include?(@pdate_1922041816), "Expression #{expr.to_s} should include #{@pdate_1922041816.to_s}" assert expr.include?(@pdate_1975060512), "Expression #{expr.to_s} should include #{@pdate_1975060512.to_s}" assert !expr.include?(@pdate_2012050803), "Expression #{expr.to_s} should not include #{@pdate_2012050803.to_s}" end def test_830_to_midnight expr = REDay.new(20,30,00,00) assert expr.include?(@pdate_200401282100), "Expression #{expr.to_s} should include #{@pdate_200401282100.to_s}" assert expr.include?(@pdate_200401280000), "Expression #{expr.to_s} should include #{@pdate_200401280000.to_s}" assert !expr.include?(@pdate_200401280001), "Expression #{expr.to_s} should not include #{@pdate_200401280001.to_s}" end def test_range_each_day_te_to_s assert_equal 'from 11:10PM to 01:20AM daily', REDay.new(23,10,1,20).to_s end def test_less_precise_argument_and_precision_policy expr = REDay.new(8,00,10,00) assert expr.include?(@pdate_20040531), \ "Expression #{expr.to_s} should include any lower precision argument by default" expr = REDay.new(8,00,10,00, false) assert !expr.include?(@pdate_20040531), \ "Expression #{expr.to_s} created with less_precise_match=false should not include any lower precision argument automatically" ## Date class which has no public hour or min methods should not cause an exception assert !expr.include?(@date_19611101), \ "Expression #{expr.to_s} created with less_precise_match=false should not hurl when given a Date instance" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/examples/schedule_tutorialtest.rb
examples/schedule_tutorialtest.rb
#!/usr/bin/ruby require 'test/unit' require 'runt' require 'schedule_tutorial' class ReminderTest < Test::Unit::TestCase include Runt def setup @schedule = Schedule.new @north_event = Event.new("north side of the street will be ticketed") north_expr = (DIWeek.new(Mon) | DIWeek.new(Wed) | DIWeek.new(Fri)) & REDay.new(8,00,11,00) @schedule.add(@north_event, north_expr) @south_event = Event.new("south side of the street will be ticketed") south_expr = (DIWeek.new(Tue) | DIWeek.new(Thu)) & REDay.new(11,30,14,00) @schedule.add(@south_event, south_expr) @mail_server = MailServer.new @reminder = Reminder.new(@schedule, @mail_server) @saturday_at_10 = PDate.min(2007,11,24,10,0,0) @monday_at_10 = PDate.min(2007,11,26,10,0,0) @tuesday_at_noon = PDate.min(2007,11,27,12,0,0) end def test_initalize assert_same @schedule, @reminder.schedule, "Expected #{@schedule} instead was #{@reminder.schedule}" assert_same @mail_server, @reminder.mail_server, "Expected #{@mail_server} instead was #{@reminder.mail_server}" end def test_send params = [@north_event, @south_event] result = @reminder.send(params) assert_email result, Reminder::TEXT + params.join(', ') end def test_check assert_equal 1, @reminder.check(@monday_at_10).size, "Unexpected size #{@reminder.check(@monday_at_10).size} returned" assert_same @north_event, @reminder.check(@monday_at_10)[0], "Expected Event #{@north_event}. Got #{@reminder.check(@monday_at_10)[0]}." assert_equal 1, @reminder.check(@tuesday_at_noon).size, "Unexpected size #{@reminder.check(@tuesday_at_noon).size} returned" assert_same @south_event, @reminder.check(@tuesday_at_noon)[0], "Expected Event #{@south_event}. Got #{@reminder.check(@tuesday_at_noon)[0]}." assert @reminder.check(@saturday_at_10).empty?, "Expected empty Array. Got #{@reminder.check(@saturday_at_10)}" end def test_run result = @reminder.run(@monday_at_10) assert_email result, Reminder::TEXT + @north_event.to_s end def assert_email(result, text) assert_equal Reminder::TO, result.to, "Unexpected value for 'to' field of Email Struct: #{result.to}" assert_equal Reminder::FROM, result.from, "Unexpected value for 'from' field of Email Struct: #{result.from}" assert_equal Reminder::SUBJECT, result.subject, "Unexpected value for 'subject' field of Email Struct: #{result.subject}" assert_equal text, result.text, "Unexpected value for 'text' field of Email Struct: #{result.text}" end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/examples/payment_reporttest.rb
examples/payment_reporttest.rb
#!/usr/bin/ruby require 'test/unit' require 'runt' require 'payment_report' class ReportTest < Test::Unit::TestCase include Runt def setup @schedule = Schedule.new # Gas payment on the first Wednesday of every month @gas_payment = Payment.new("Gas", 234) @gas_expr = DIMonth.new(First, Wednesday) @schedule.add(@gas_payment, @gas_expr) # Insurance payment every year on January 7th @insurance_payment = Payment.new("Insurance", 345) @insurance_expr = REYear.new(1, 7, 1, 7) @schedule.add(@insurance_payment, @insurance_expr) @report = Report.new(@schedule) end def test_initialize assert_equal @schedule, @report.schedule end def test_list range = PDate.day(2008, 1, 1)..PDate.day(2008,1,31) result = @report.list(range) assert_equal(2, result.size) assert_equal(@gas_payment, result[PDate.day(2008, 1, 2)][0]) assert_equal(@insurance_payment, result[PDate.day(2008, 1, 7)][0]) end end class PaymentTest < Test::Unit::TestCase include Runt def test_initialize p = Payment.new "Foo", 12 assert_equal "Foo", p.id assert_equal 12, p.amount end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/examples/schedule_tutorial.rb
examples/schedule_tutorial.rb
#!/usr/bin/ruby require 'runt' class Reminder TO = "me@myselfandi.com" FROM = "reminder@daemon.net" SUBJECT = "Move your car!" TEXT = "Warning: " attr_reader :schedule, :mail_server def initialize(schedule,mail_server) @schedule = schedule @mail_server = mail_server end def run(date) result = self.check(date) self.send(result) if !result.empty? end def check(date) puts "Checking the schedule..." if $DEBUG return @schedule.events(date) end def send(events) text = TEXT + events.join(', ') return @mail_server.send(TO, FROM, SUBJECT, text) end end class MailServer Struct.new("Email",:to,:from,:subject,:text) def send(to, from, subject, text) puts "Sending message TO: #{to} FROM: #{from} RE: #{subject}..." if $DEBUG Struct::Email.new(to, from, subject, text) # etc... end end if __FILE__ == $0 include Runt schedule = Schedule.new north_event = Event.new("north side") north_expr = (DIWeek.new(Mon) | DIWeek.new(Wed) | DIWeek.new(Fri)) & REDay.new(8,00,11,00) schedule.add(north_event, north_expr) south_event = Event.new("south side") south_expr = (DIWeek.new(Tue) | DIWeek.new(Thu)) & REDay.new(11,30,14,00) schedule.add(south_event, south_expr) reminder = Reminder.new(schedule, MailServer.new) while true sleep 15.minutes reminder.run Time.now end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/examples/reminder.rb
examples/reminder.rb
#!/usr/bin/ruby # NOTE this is slightly broken; it is in the process of being fixed base = File.basename(Dir.pwd) if base == "examples" || base =~ /runt/ Dir.chdir("..") if base == "examples" $LOAD_PATH.unshift(Dir.pwd + '/lib') Dir.chdir("examples") if base =~ /runt/ end require 'runt' class Reminder include Runt def initialize(schedule) @schedule=schedule end def next_times(event,end_point,now=Time.now) @schedule.dates(event,DateRange.new(now,end_point)) end end # start of range whose occurrences we want to list # TODO fix Runt so this can be done with Time instead # e.g., now=Time.now #now=Time.parse("13:00") #now.date_precision=Runt::DPrecision::MIN now=Runt::PDate.min(2006,12,8,13,00) # end of range soon=(now + 10.minutes) # Sanity check print "start: #{now.to_s} (#{now.date_precision}) end: #{soon.to_s} (#{soon.date_precision})\n" # # Schedule used to house TemporalExpression describing the recurrence from # which we'd list to generate a list of dates. In this example, some Event # occuring every 5 minutes. # schedule=Runt::Schedule.new # Some event whose schedule we're interested in event=Runt::Event.new("whatever") # Add the event to the schedule ( # NOTE: any Object that is a sensible Hash key can be used schedule.add(event,Runt::EveryTE.new(now,5.minutes)) # Example domain Object using Runt reminder=Reminder.new(schedule) # Call our domain Object with the start and end times and the event # in which we're interested #puts "times (inclusive) = #{reminder.next_times(event,soon,now).join('\n')}" puts "times (inclusive):" reminder.next_times(event,soon,now).each{|t| puts t}
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/examples/payment_report.rb
examples/payment_report.rb
#!/usr/bin/ruby require 'runt' class Report attr_reader :schedule def initialize(schedule) @schedule = schedule end def list(range) result = {} range.each do |dt| events = @schedule.events(dt) result[dt]=events unless events.empty? end result end end class Payment < Runt::Event attr_accessor :amount def initialize(id, amount) super(id) @amount = amount end end if __FILE__ == $0 include Runt schedule = Schedule.new # Gas payment on the first Wednesday of every month gas_payment = Payment.new("Gas", 234) gas_expr = DIMonth.new(First, Wednesday) schedule.add(gas_payment, gas_expr) # Insurance payment every year on January 7th insurance_payment = Payment.new("Insurance", 345) insurance_expr = REYear.new(1, 7, 1, 7) schedule.add(insurance_payment, insurance_expr) # Run a report report = Report.new(schedule) result = report.list(PDate.day(2008, 1, 1)..PDate.day(2008,1,31)) result.keys.sort.each do |dt| unless result[dt].empty? then print "#{dt.ctime} - " result[dt].each do |event| puts "#{event.id}, $#{event.amount}" end end end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt.rb
lib/runt.rb
#!/usr/bin/env ruby # :title:Runt -- Ruby Temporal Expressions # # == Runt -- Ruby Temporal Expressions # # The usage and design patterns expressed in this library are mostly...*uhm*.. # <em>entirely</em>..*cough*...based on a series of # <tt>articles</tt>[http://www.martinfowler.com] by Martin Fowler. # # It highly recommended that anyone using Runt (or writing # object-oriented software :) take a moment to peruse the wealth of useful info # that Fowler has made publicly available: # # * An excellent introductory summation of temporal <tt>patterns</tt>[http://martinfowler.com/ap2/timeNarrative.html] # * Recurring event <tt>pattern</tt>[http://martinfowler.com/apsupp/recurring.pdf] # # Also, for those of you (like me, for example) still chained in your cubicle and forced # to write <tt>Java</tt>[http://java.sun.com] code, check out the original version of # project called <tt>ChronicJ</tt>[http://chronicj.org]. # # --- # Author:: Matthew Lipper (mailto:mlipper@gmail.com) # Copyright:: Copyright (c) 2004 Digital Clash, LLC # License:: See LICENSE.txt # # = Warranty # # This software is provided "as is" and without any express or # implied warranties, including, without limitation, the implied # warranties of merchantibility and fitness for a particular # purpose. require 'yaml' require 'time' require 'date' require "runt/version" require "runt/dprecision" require "runt/pdate" require "runt/temporalexpression" require "runt/schedule" require "runt/daterange" require "runt/sugar" require "runt/expressionbuilder" # # The Runt module is the main namespace for all Runt modules and classes. Using # require statements, it makes the entire Runt library available.It also # defines some new constants and exposes some already defined in the standard # library classes <tt>Date</tt> and <tt>DateTime</tt>. # # <b>See also</b> runt/sugar_rb which re-opens this module and adds # some additional functionality # # <b>See also</b> date.rb # module Runt class << self def day_name(number) Date::DAYNAMES[number] end def month_name(number) Date::MONTHNAMES[number] end def format_time(date) date.strftime('%I:%M%p') end def format_date(date) date.ctime end # # Cut and pasted from activesupport-1.2.5/lib/inflector.rb # def ordinalize(number) if (number.to_i==-1) 'last' elsif (number.to_i==-2) 'second to last' elsif (11..13).include?(number.to_i % 100) "#{number}th" else case number.to_i % 10 when 1 then "#{number}st" when 2 then "#{number}nd" when 3 then "#{number}rd" else "#{number}th" end end end end #Yes it's true, I'm a big idiot! Sunday = Date::DAYNAMES.index("Sunday") Monday = Date::DAYNAMES.index("Monday") Tuesday = Date::DAYNAMES.index("Tuesday") Wednesday = Date::DAYNAMES.index("Wednesday") Thursday = Date::DAYNAMES.index("Thursday") Friday = Date::DAYNAMES.index("Friday") Saturday = Date::DAYNAMES.index("Saturday") Sun = Date::ABBR_DAYNAMES.index("Sun") Mon = Date::ABBR_DAYNAMES.index("Mon") Tue = Date::ABBR_DAYNAMES.index("Tue") Wed = Date::ABBR_DAYNAMES.index("Wed") Thu = Date::ABBR_DAYNAMES.index("Thu") Fri = Date::ABBR_DAYNAMES.index("Fri") Sat = Date::ABBR_DAYNAMES.index("Sat") January = Date::MONTHNAMES.index("January") February = Date::MONTHNAMES.index("February") March = Date::MONTHNAMES.index("March") April = Date::MONTHNAMES.index("April") May = Date::MONTHNAMES.index("May") June = Date::MONTHNAMES.index("June") July = Date::MONTHNAMES.index("July") August = Date::MONTHNAMES.index("August") September = Date::MONTHNAMES.index("September") October = Date::MONTHNAMES.index("October") November = Date::MONTHNAMES.index("November") December = Date::MONTHNAMES.index("December") First = 1 Second = 2 Third = 3 Fourth = 4 Fifth = 5 Sixth = 6 Seventh = 7 Eighth = 8 Eigth = 8 # Will be removed in v0.9.0 Ninth = 9 Tenth = 10 private class ApplyLast #:nodoc: def initialize @negate=Proc.new{|n| n*-1} end def [](arg) @negate.call(arg) end end LastProc = ApplyLast.new public Last = LastProc[First] Last_of = LastProc[First] Second_to_last = LastProc[Second] end # # Add precision +Runt::DPrecision+ to standard library classes Date and DateTime # (which is a subclass of Date). Also, add an include? method for interoperability # with +Runt::TExpr+ classes # class Date include Runt alias_method :include?, :eql? attr_accessor :date_precision def date_precision if @date_precision.nil? then if self.class == DateTime then @date_precision = Runt::DPrecision::SEC else @date_precision = Runt::DPrecision::DAY end end @date_precision end end # # Add the ability to use Time class # # Contributed by Paul Wright # class Time include Runt attr_accessor :date_precision alias_method :old_initialize, :initialize def initialize(*args) if(args[0].instance_of?(Runt::DPrecision::Precision)) @precision=args.shift else @precision=Runt::DPrecision::SEC end old_initialize(*args) end alias :old_to_yaml :to_yaml def to_yaml(options) if self.instance_variables.empty? self.old_to_yaml(options) else Time.old_parse(self.to_s).old_to_yaml(options) end end class << self alias_method :old_parse, :parse def parse(*args) precision=Runt::DPrecision::DEFAULT if(args[0].instance_of?(Runt::DPrecision::Precision)) precision=args.shift end _parse=old_parse(*args) _parse.date_precision=precision _parse end end def date_precision return @date_precision unless @date_precision.nil? return Runt::DPrecision::DEFAULT end end # # Useful shortcuts! # # Originally contributed by Ara T. Howard who is pretty sure he got the idea from # somewhere else. :-) # # Patched by rgeerts in GH pull-request #17 # class Numeric #:nodoc: def microseconds() Float(self * (10 ** -6)) end unless self.instance_methods.include?(:microseconds) def milliseconds() Float(self * (10 ** -3)) end unless self.instance_methods.include?(:milliseconds) def seconds() self end unless self.instance_methods.include?(:seconds) def minutes() 60 * seconds end unless self.instance_methods.include?(:minutes) def hours() 60 * minutes end unless self.instance_methods.include?(:hours) def days() 24 * hours end unless self.instance_methods.include?(:days) def weeks() 7 * days end unless self.instance_methods.include?(:weeks) def months() 30 * days end unless self.instance_methods.include?(:months) def years() 365 * days end unless self.instance_methods.include?(:years) def decades() 10 * years end unless self.instance_methods.include?(:decades) # This causes RDoc to hurl: %w[ microseconds milliseconds seconds minutes hours days weeks months years decades ].each{|m| alias_method m.chop, m} end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/pdate.rb
lib/runt/pdate.rb
#!/usr/bin/env ruby require 'date' require 'runt' module Runt # :title:PDate # == PDate # Date and DateTime with explicit precision. # # Based the <tt>pattern</tt>[http://martinfowler.com/ap2/timePoint.html] by Martin Fowler. # # # Author:: Matthew Lipper class PDate < DateTime include Comparable include DPrecision attr_accessor :date_precision class << self def civil(*args) precision=nil if(args[0].instance_of?(DPrecision::Precision)) precision = args.shift else return PDate::sec(*args) end pdate = super(*args) pdate.date_precision = precision pdate end def parse(*args) opts = args.last.is_a?(Hash) ? args.pop : {} pdate = super(*args) pdate.date_precision = opts[:precision] || opts[:date_precision] pdate end alias_method :new, :civil end def include?(expr) eql?(expr) end def + (n) raise TypeError, 'expected numeric' unless n.kind_of?(Numeric) ndays = n case @date_precision when YEAR then return DPrecision::to_p(PDate::civil(year+n,month,day),@date_precision) when MONTH then return DPrecision::to_p((self.to_date>>n),@date_precision) when WEEK then ndays = n*7 when DAY then ndays = n when HOUR then ndays = n*(1.to_r/24) when MIN then ndays = n*(1.to_r/1440) when SEC then ndays = n*(1.to_r/86400) when MILLI then ndays = n*(1.to_r/86400000) end DPrecision::to_p((self.to_date + ndays),@date_precision) end def - (x) case x when Numeric then return self+(-x) when Date then return super(DPrecision::to_p(x,@date_precision)) end raise TypeError, 'expected numeric or date' end def <=> (other) result = nil raise "I'm broken #{self.to_s}" if @date_precision.nil? if(!other.nil? && other.respond_to?("date_precision") && other.date_precision>@date_precision) result = super(DPrecision::to_p(other,@date_precision)) else result = super(other) end puts "self<#{self.to_s}><=>other<#{other.to_s}> => #{result}" if $DEBUG result end def succ result = self + 1 end def to_date (self.date_precision > DAY) ? DateTime.new(self.year,self.month,self.day,self.hour,self.min,self.sec) : Date.new(self.year, self.month, self.day) end def PDate.year(yr,*ignored) PDate.civil(YEAR, yr, MONTH.min_value, DAY.min_value ) end def PDate.month( yr,mon,*ignored ) PDate.civil(MONTH, yr, mon, DAY.min_value ) end def PDate.week( yr,mon,day,*ignored ) #LJK: need to calculate which week this day implies, #and then move the day back to the *first* day in that week; #note that since rfc2445 defaults to weekstart=monday, I'm #going to use commercial day-of-week raw = PDate.day(yr, mon, day) cooked = PDate.commercial(raw.cwyear, raw.cweek, 1) PDate.civil(WEEK, cooked.year, cooked.month, cooked.day) end def PDate.day( yr,mon,day,*ignored ) PDate.civil(DAY, yr, mon, day ) end def PDate.hour( yr,mon,day,hr=HOUR.min_value,*ignored ) PDate.civil(HOUR, yr, mon, day,hr,MIN.min_value, SEC.min_value) end def PDate.min( yr,mon,day,hr=HOUR.min_value,min=MIN.min_value,*ignored ) PDate.civil(MIN, yr, mon, day,hr,min, SEC.min_value) end def PDate.sec( yr,mon,day,hr=HOUR.min_value,min=MIN.min_value,sec=SEC.min_value,*ignored ) PDate.civil(SEC, yr, mon, day,hr,min, sec) end def PDate.millisecond( yr,mon,day,hr,min,sec,ms,*ignored ) PDate.civil(SEC, yr, mon, day,hr,min, sec, ms, *ignored) #raise "Not implemented yet." end def PDate.default(*args) PDate.civil(DEFAULT, *args) end #FIXME: marshall broken in 1.9 # # Custom dump which preserves DatePrecision # # Author:: Jodi Showers # def marshal_dump [date_precision, ajd, start, offset] end #FIXME: marshall broken in 1.9 # # Custom load which preserves DatePrecision # # Author:: Jodi Showers # def marshal_load(dumped_obj) @date_precision, @ajd, @sg, @of=dumped_obj end end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/version.rb
lib/runt/version.rb
module Runt VERSION = "0.9.0" end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/expressionbuilder.rb
lib/runt/expressionbuilder.rb
require 'runt' # Convenience class for building temporal expressions in a more # human-friendly way. Used in conjunction with shortcuts defined in the # sugar.rb file, this allows one to create expressions like the following: # # b = ExpressionBuilder.new # expr = b.define do # occurs daily_8_30am_to_9_45am # on tuesday # possibly wednesday # end # # This equivalent to: # # expr = REDay.new(8,30,9,45) & DIWeek.new(Tuesday) | DIWeek.new(Wednesday) # # ExpressionBuilder creates expressions by evaluating a block passed to the # :define method. From inside the block, methods :occurs, :on, :every, :possibly, # and :maybe can be called with a temporal expression which will be added to # a composite expression as follows: # # * <b>:on</b> - creates an "and" (&) # * <b>:possibly</b> - creates an "or" (|) # * <b>:except</b> - creates a "not" (-) # * <b>:every</b> - alias for :on method # * <b>:occurs</b> - alias for :on method # * <b>:maybe</b> - alias for :possibly method # class ExpressionBuilder include Runt attr_accessor :ctx def initialize @ctx = nil end def define(&block) instance_eval(&block) end def on(expr) add(expr, :&) end def add(expr, op) @ctx ||= expr @ctx = @ctx.send(op, expr) unless @ctx == expr @ctx # explicit return, previous line may not execute end def except(expr) add(expr, :-) end def possibly(expr) add(expr, :|) end alias_method :every, :on alias_method :occurs, :on alias_method :maybe, :possibly end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/sugar.rb
lib/runt/sugar.rb
#!/usr/bin/env ruby # # # == Overview # # This file provides an optional extension to the Runt module which # provides convenient shortcuts for commonly used temporal expressions. # # Several methods for creating new temporal expression instances are added # to a client class by including the Runt module. # # === Shortcuts # # Shortcuts are implemented by pattern matching done in method_missing for # the Runt module. Generally speaking, range expressions start with "daily_", # "weekly_", "yearly_", etc. # # Times use the format /\d{1,2}_\d{2}[ap]m/ where the first digits represent hours # and the second digits represent minutes. Note that hours are always within the # range of 1-12 and may be one or two digits. Minutes are always two digits # (e.g. '03' not just '3') and are always followed by am or pm (lowercase). # # # class MyClass # include Runt # # def some_method # # Daily from 4:02pm to 10:20pm or anytime Tuesday # expr = daily_4_02pm_to_10_20pm() | tuesday() # ... # end # ... # end # # The following documents the syntax for particular temporal expression classes. # # === REDay # # daily_<start hour>_<start minute>_to_<end hour>_<end minute> # # Example: # # self.daily_10_00am_to_1:30pm() # # is equivilant to # # REDay.new(10,00,13,30) # # === REWeek # # weekly_<start day>_to_<end day> # # Example: # # self.weekly_tuesday_to_thrusday() # # is equivilant to # # REWeek.new(Tuesday, Thrusday) # # === REMonth # # monthly_<start numeric ordinal>_to_<end numeric ordinal> # # Example: # # self.monthly_23rd_to_29th() # # is equivilant to # # REMonth.new(23, 29) # # === REYear # # self.yearly_<start month>_<start day>_to_<end month>_<end day>() # # Example: # # self.yearly_march_15_to_june_1() # # is equivilant to # # REYear.new(March, 15, June, 1) # # === DIWeek # # self.<day name>() # # Example: # # self.friday() # # is equivilant to # # DIWeek.new(Friday) # # === DIMonth # # self.<lowercase ordinal>_<day name>() # # Example: # # self.first_saturday() # self.last_tuesday() # # is equivilant to # # DIMonth.new(First, Saturday) # DIMonth.new(Last, Tuesday) # # === AfterTE # # self.after(date [, inclusive]) # # Example: # # self.after(date) # self.after(date, true) # # is equivilant to # # AfterTE.new(date) # AfterTE.new(date, true) # # === BeforeTE # # self.before(date [, inclusive]) # # Example: # # self.before(date) # self.before(date, true) # # is equivilant to # # BeforeTE.new(date) # BeforeTE.new(date, true) # require 'runt' module Runt MONTHS = '(january|february|march|april|may|june|july|august|september|october|november|december)' DAYS = '(sunday|monday|tuesday|wednesday|thursday|friday|saturday)' WEEK_OF_MONTH_ORDINALS = '(first|second|third|fourth|last|second_to_last)' ORDINAL_SUFFIX = '(?:st|nd|rd|th)' ORDINAL_ABBR = '(st|nd|rd|th)' class << self def const(string) self.const_get(string.capitalize) end end def method_missing(name, *args, &block) #puts "method_missing(#{name},#{args},#{block}) => #{result}" case name.to_s when /^daily_(\d{1,2})_(\d{2})([ap]m)_to_(\d{1,2})_(\d{2})([ap]m)$/ # REDay st_hr, st_min, st_m, end_hr, end_min, end_m = $1, $2, $3, $4, $5, $6 args = parse_time(st_hr, st_min, st_m) args.concat(parse_time(end_hr, end_min, end_m)) return REDay.new(*args) when Regexp.new('^weekly_' + DAYS + '_to_' + DAYS + '$') # REWeek st_day, end_day = $1, $2 return REWeek.new(Runt.const(st_day), Runt.const(end_day)) when Regexp.new('^monthly_(\d{1,2})' + ORDINAL_SUFFIX + '_to_(\d{1,2})' \ + ORDINAL_SUFFIX + '$') # REMonth st_day, end_day = $1, $2 return REMonth.new(st_day, end_day) when Regexp.new('^yearly_' + MONTHS + '_(\d{1,2})_to_' + MONTHS + '_(\d{1,2})$') # REYear st_mon, st_day, end_mon, end_day = $1, $2, $3, $4 return REYear.new(Runt.const(st_mon), st_day, Runt.const(end_mon), end_day) when Regexp.new('^' + DAYS + '$') # DIWeek return DIWeek.new(Runt.const(name.to_s)) when Regexp.new(WEEK_OF_MONTH_ORDINALS + '_' + DAYS) # DIMonth ordinal, day = $1, $2 return DIMonth.new(Runt.const(ordinal), Runt.const(day)) else # You're hosed super end end # Shortcut for AfterTE(date, ...).new def after(date, inclusive=false) AfterTE.new(date, inclusive) end # Shortcut for BeforeTE(date, ...).new def before(date, inclusive=false) BeforeTE.new(date, inclusive) end def parse_time(hour, minute, ampm) hour = hour.to_i + 12 if ampm =~ /pm/ [hour.to_i, minute.to_i] end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/daterange.rb
lib/runt/daterange.rb
#!/usr/bin/env ruby require 'date' require 'runt' module Runt # :title:DateRange # == DateRange # # # Based the <tt>range</tt>[http://martinfowler.com/ap2/range.html] pattern by Martin Fowler. # # # # Author:: Matthew Lipper class DateRange < Range include DPrecision attr_reader :start_expr, :end_expr def initialize(start_expr, end_expr,exclusive=false) super(start_expr, end_expr,exclusive) @start_expr, @end_expr = start_expr, end_expr end def include?(obj) return super(obj.min) && super(obj.max) if obj.kind_of? Range return super(obj) end def overlap?(obj) return true if( member?(obj) || include?(obj.min) || include?(obj.max) ) return true if( obj.kind_of?(Range) && obj.include?(self) ) false end def empty? return @start_expr >= @end_expr end def gap(obj) return EMPTY if self.overlap? obj lower=nil higher=nil if((self<=>obj)<0) lower=self higher=obj else lower=obj higher=self end return DateRange.new((lower.end_expr+1),(higher.start_expr-1)) end def <=>(other) return @start_expr <=> other.start_expr if(@start_expr != other.start_expr) return @end_expr <=> other.end_expr end def min; @start_expr end def max; @end_expr end def to_s; @start_expr.to_s + " " + @end_expr.to_s end EMPTY = DateRange.new(PDate.day(2004,2,2),PDate.day(2004,2,1)) end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/dprecision.rb
lib/runt/dprecision.rb
#!/usr/bin/env ruby require 'runt' require 'date' module Runt # :title:DPrecision # == DPrecision # Module providing automatic precisioning of Date, DateTime, and PDate classes. # # Inspired by a <tt>pattern</tt>[http://martinfowler.com/ap2/timePoint.html] by Martin Fowler. # # # Author:: Matthew Lipper module DPrecision def DPrecision.to_p(date,prec=DEFAULT) has_p = date.respond_to?(:date_precision) #puts "DPrecision.to_p(#{date.class}<#{has_p ? date.date_precision : nil}>,#{prec})" return date if PDate == date.class && (prec == date.date_precision) case prec when MIN then PDate.min(*DPrecision.explode(date,prec)) when DAY then PDate.day(*DPrecision.explode(date,prec)) when HOUR then PDate.hour(*DPrecision.explode(date,prec)) when WEEK then PDate.week(*DPrecision.explode(date,prec)) when MONTH then PDate.month(*DPrecision.explode(date,prec)) when YEAR then PDate.year(*DPrecision.explode(date,prec)) when SEC then PDate.sec(*DPrecision.explode(date,prec)) when MILLI then date #raise "Not implemented." else PDate.default(*DPrecision.explode(date,prec)) end end def DPrecision.explode(date,prec) result = [date.year,date.month,date.day] if(date.respond_to?(:hour)) result << date.hour << date.min << date.sec else result << 0 << 0 << 0 end result end #Simple value class for keeping track of precisioned dates class Precision include Comparable attr_reader :precision private_class_method :new #Some constants w/arbitrary integer values used internally for comparisions YEAR_PREC = 0 MONTH_PREC = 1 WEEK_PREC = 2 DAY_PREC = 3 HOUR_PREC = 4 MIN_PREC = 5 SEC_PREC = 6 MILLI_PREC = 7 #String values for display LABEL = { YEAR_PREC => "YEAR", MONTH_PREC => "MONTH", WEEK_PREC => "WEEK", DAY_PREC => "DAY", HOUR_PREC => "HOUR", MIN_PREC => "MINUTE", SEC_PREC => "SECOND", MILLI_PREC => "MILLISECOND"} #Minimun values that precisioned fields get set to FIELD_MIN = { YEAR_PREC => 1, MONTH_PREC => 1, WEEK_PREC => 1, DAY_PREC => 1, HOUR_PREC => 0, MIN_PREC => 0, SEC_PREC => 0, MILLI_PREC => 0} def Precision.year new(YEAR_PREC) end def Precision.month new(MONTH_PREC) end def Precision.week new(WEEK_PREC) end def Precision.day new(DAY_PREC) end def Precision.hour new(HOUR_PREC) end def Precision.min new(MIN_PREC) end def Precision.sec new(SEC_PREC) end def Precision.millisec new(MILLI_PREC) end def min_value() FIELD_MIN[@precision] end def initialize(prec) @precision = prec end def <=>(other) self.precision <=> other.precision end def ===(other) self.precision == other.precision end def to_s "DPrecision::#{self.label}" end def label LABEL[@precision] end end #Pseudo Singletons: YEAR = Precision.year MONTH = Precision.month WEEK = Precision.week DAY = Precision.day HOUR = Precision.hour MIN = Precision.min SEC = Precision.sec MILLI = Precision.millisec DEFAULT=MIN end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/temporalexpression.rb
lib/runt/temporalexpression.rb
#!/usr/bin/env ruby require 'date' require 'runt/dprecision' require 'runt/pdate' require 'pp' # # Author:: Matthew Lipper module Runt # # 'TExpr' is short for 'TemporalExpression' and are inspired by the recurring event # <tt>pattern</tt>[http://martinfowler.com/apsupp/recurring.pdf] # described by Martin Fowler. Essentially, they provide a pattern language for # specifying recurring events using set expressions. # # See also [tutorial_te.rdoc] module TExpr # Returns true or false depending on whether this TExpr includes the supplied # date expression. def include?(date_expr); false end def to_s; "TExpr" end def or (arg) if self.kind_of?(Union) self.add(arg) else yield Union.new.add(self).add(arg) end end def and (arg) if self.kind_of?(Intersect) self.add(arg) else yield Intersect.new.add(self).add(arg) end end def minus (arg) yield Diff.new(self,arg) end def | (expr) self.or(expr){|adjusted| adjusted } end def & (expr) self.and(expr){|adjusted| adjusted } end def - (expr) self.minus(expr){|adjusted| adjusted } end # Contributed by Emmett Shear: # Returns an Array of Date-like objects which occur within the supplied # DateRange. Will stop calculating dates once a number of dates equal # to the optional attribute limit are found. (A limit of zero will collect # all matching dates in the date range.) def dates(date_range, limit=0) result = [] date_range.each do |date| result << date if self.include? date if limit > 0 and result.size == limit break end end result end end # Base class for TExpr classes that can be composed of other # TExpr objects imlpemented using the <tt>Composite(GoF)</tt> pattern. class Collection include TExpr attr_reader :expressions def initialize(expressions = []) @expressions = expressions end def ==(other) if other.is_a?(Collection) o_exprs = other.expressions.dup expressions.each do |e| return false unless i = o_exprs.index(e) o_exprs.delete_at(i) end o_exprs.each {|e| return false unless i == expressions.index(e)} return true else super(other) end end def add(anExpression) @expressions.push anExpression self end # Will return true if the supplied object overlaps with the range used to # create this instance def overlap?(date_expr) @expressions.each do | interval | return true if date_expr.overlap?(interval) end false end def to_s if !@expressions.empty? && block_given? first_expr, next_exprs = yield result = '' @expressions.map do |expr| if @expressions.first===expr result = first_expr + expr.to_s else result = result + next_exprs + expr.to_s end end result else 'empty' end end def display puts "I am a #{self.class} containing:" @expressions.each do |ex| pp "#{ex.class}" end end end # Composite TExpr that will be true if <b>any</b> of it's # component expressions are true. class Union < Collection def include?(aDate) @expressions.each do |expr| return true if expr.include?(aDate) end false end def to_s super {['every ',' or ']} end end # Composite TExpr that will be true only if <b>all</b> it's # component expressions are true. class Intersect < Collection def include?(aDate) result = false @expressions.each do |expr| return false unless (result = expr.include?(aDate)) end result end def to_s super {['every ', ' and ']} end end # TExpr that will be true only if the first of # its two contained expressions is true and the second is false. class Diff include TExpr attr_reader :expr1, :expr2 def initialize(expr1, expr2) @expr1 = expr1 @expr2 = expr2 end def ==(o) o.is_a?(Diff) ? expr1 == o.expr1 && expr2 == o.expr2 : super(o) end def include?(aDate) return false unless (@expr1.include?(aDate) && !@expr2.include?(aDate)) true end def to_s @expr1.to_s + ' except for ' + @expr2.to_s end end # TExpr that provides for inclusion of an arbitrary date. class TemporalDate include TExpr attr_reader :date_expr def initialize(date_expr) @date_expr = date_expr end def ==(o) o.is_a?(TemporalDate) ? date_expr == o.date_expr : super(o) end # Will return true if the supplied object is == to that which was used to # create this instance def include?(date_expr) return date_expr.include?(@date_expr) if date_expr.respond_to?(:include?) return true if @date_expr == date_expr false end def to_s @date_expr.to_s end end # TExpr that provides a thin wrapper around built-in Ruby <tt>Range</tt> functionality # facilitating inclusion of an arbitrary range in a temporal expression. # # See also: Range class TemporalRange < TemporalDate ## Will return true if the supplied object is included in the range used to ## create this instance def include?(date_expr) return @date_expr.include?(date_expr) end def ==(o) o.is_a?(TemporalRange) ? date_expr == o.date_expr : super(o) end # Will return true if the supplied object overlaps with the range used to # create this instance def overlap?(date_expr) @date_expr.each do | interval | return true if date_expr.include?(interval) end false end end ####################################################################### # Utility methods common to some expressions module TExprUtils def week_in_month(day_in_month) ((day_in_month - 1) / 7) + 1 end def days_left_in_month(date) return max_day_of_month(date) - date.day end def max_day_of_month(date) # Contributed by Justin Cunningham who took it verbatim from the Rails # ActiveSupport::CoreExtensions::Time::Calculations::ClassMethods module # days_in_month method. month = date.month year = date.year if month == 2 !year.nil? && (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) ? 29 : 28 elsif month <= 7 month % 2 == 0 ? 30 : 31 else month % 2 == 0 ? 31 : 30 end end def week_matches?(index,date) if(index > 0) return week_from_start_matches?(index,date) else return week_from_end_matches?(index,date) end end def week_from_start_matches?(index,date) week_in_month(date.day)==index end def week_from_end_matches?(index,date) n = days_left_in_month(date) + 1 week_in_month(n)==index.abs end end # TExpr that provides support for building a temporal # expression using the form: # # DIMonth.new(1,0) # # where the first argument is the week of the month and the second # argument is the wday of the week as defined by the 'wday' method # in the standard library class Date. # # A negative value for the week of the month argument will count # backwards from the end of the month. So, to match the last Saturday # of the month # # DIMonth.new(-1,6) # # Using constants defined in the base Runt module, you can re-write # the first example above as: # # DIMonth.new(First,Sunday) # # and the second as: # # DIMonth.new(Last,Saturday) # # See also: Date, Runt class DIMonth include TExpr include TExprUtils attr_reader :day_index, :week_of_month_index def initialize(week_of_month_index,day_index) @day_index = day_index @week_of_month_index = week_of_month_index end def ==(o) o.is_a?(DIMonth) ? day_index == o.day_index && week_of_month_index == o.week_of_month_index : super(o) end def include?(date) ( day_matches?(date) ) && ( week_matches?(@week_of_month_index,date) ) end def to_s "#{Runt.ordinalize(@week_of_month_index)} #{Runt.day_name(@day_index)} of the month" end private def day_matches?(date) @day_index == date.wday end end # TExpr that matches days of the week where the first argument # is an integer denoting the ordinal day of the week. Valid values are 0..6 where # 0 == Sunday and 6==Saturday # # For example: # # DIWeek.new(0) # # Using constants defined in the base Runt module, you can re-write # the first example above as: # # DIWeek.new(Sunday) # # See also: Date, Runt class DIWeek include TExpr VALID_RANGE = 0..6 attr_reader :ordinal_weekday def initialize(ordinal_weekday) unless VALID_RANGE.include?(ordinal_weekday) raise ArgumentError, 'invalid ordinal day of week' end @ordinal_weekday = ordinal_weekday end def ==(o) o.is_a?(DIWeek) ? ordinal_weekday == o.ordinal_weekday : super(o) end def include?(date) @ordinal_weekday == date.wday end def to_s "#{Runt.day_name(@ordinal_weekday)}" end end # TExpr that matches days of the week within one # week only. # # If start and end day are equal, the entire week will match true. # # See also: Date class REWeek include TExpr VALID_RANGE = 0..6 attr_reader :start_day, :end_day # Creates a REWeek using the supplied start # day(range = 0..6, where 0=>Sunday) and an optional end # day. If an end day is not supplied, the maximum value # (6 => Saturday) is assumed. def initialize(start_day,end_day=6) validate(start_day,end_day) @start_day = start_day @end_day = end_day end def ==(o) o.is_a?(REWeek) ? start_day == o.start_day && end_day == o.end_day : super(o) end def include?(date) return true if all_week? if @start_day < @end_day @start_day<=date.wday && @end_day>=date.wday else (@start_day<=date.wday && 6 >=date.wday) || (0 <=date.wday && @end_day >=date.wday) end end def to_s return "all week" if all_week? "#{Runt.day_name(@start_day)} through #{Runt.day_name(@end_day)}" end private def all_week? return true if @start_day==@end_day end def validate(start_day,end_day) unless VALID_RANGE.include?(start_day)&&VALID_RANGE.include?(end_day) raise ArgumentError, 'start and end day arguments must be in the range #{VALID_RANGE.to_s}.' end end end # # TExpr that matches date ranges within a single year. Assumes that the start # and end parameters occur within the same year. # # class REYear # Sentinel value used to denote that no specific day was given to create # the expression. NO_DAY = 0 include TExpr attr_accessor :start_month, :start_day, :end_month, :end_day # # == Synopsis # # REYear.new(start_month [, (start_day | end_month), ...] # # == Args # # One or two arguments given:: # # +start_month+:: # Start month. Valid values are 1..12. When no other parameters are given # this value will be used for the end month as well. Matches the entire # month through the ending month. # +end_month+:: # End month. Valid values are 1..12. When given in two argument form # will match through the entire month. # # Three or four arguments given:: # # +start_month+:: # Start month. Valid values are 1..12. # +start_day+:: # Start day. Valid values are 1..31, depending on the month. # +end_month+:: # End month. Valid values are 1..12. If a fourth argument is not given, # this value will cover through the entire month. # +end_day+:: # End day. Valid values are 1..31, depending on the month. # # == Description # # Create a new REYear expression expressing a range of months or days # within months within a year. # # == Usage # # # Creates the range March 12th through May 23rd # expr = REYear.new(3,12,5,23) # # # Creates the range March 1st through May 31st # expr = REYear.new(3,5) # # # Creates the range March 12th through May 31st # expr = REYear.new(3,12,5) # # # Creates the range March 1st through March 30th # expr = REYear.new(3) # def initialize(start_month, *args) @start_month = start_month if (args.nil? || args.size == NO_DAY) then # One argument given @end_month = start_month @start_day = NO_DAY @end_day = NO_DAY else case args.size when 1 @end_month = args[0] @start_day = NO_DAY @end_day = NO_DAY when 2 @start_day = args[0] @end_month = args[1] @end_day = NO_DAY when 3 @start_day = args[0] @end_month = args[1] @end_day = args[2] else raise "Invalid number of var args: 1 or 3 expected, #{args.size} given" end end @same_month_dates_provided = (@start_month == @end_month) && (@start_day!=NO_DAY && @end_day != NO_DAY) end def ==(o) o.is_a?(REYear) ? start_day == o.start_day && end_day == o.end_day && start_month == o.start_month && end_month == o.end_month : super(o) end def include?(date) return same_start_month_include_day?(date) \ && same_end_month_include_day?(date) if @same_month_dates_provided is_between_months?(date) || (same_start_month_include_day?(date) || same_end_month_include_day?(date)) end def save "Runt::REYear.new(#{@start_month}, #{@start_day}, #{@end_month}, #{@end_day})" end def to_s "#{Runt.month_name(@start_month)} #{Runt.ordinalize(@start_day)} " + "through #{Runt.month_name(@end_month)} #{Runt.ordinalize(@end_day)}" end private def is_between_months?(date) (date.mon > @start_month) && (date.mon < @end_month) end def same_end_month_include_day?(date) return false unless (date.mon == @end_month) (@end_day == NO_DAY) || (date.day <= @end_day) end def same_start_month_include_day?(date) return false unless (date.mon == @start_month) (@start_day == NO_DAY) || (date.day >= @start_day) end end # TExpr that matches periods of the day with minute # precision. If the start hour is greater than the end hour, than end hour # is assumed to be on the following day. # # NOTE: By default, this class will match any date expression whose # precision is less than or equal to DPrecision::DAY. To override # this behavior, pass the optional fifth constructor argument the # value: false. # # When the less_precise_match argument is true, the # date-like object passed to :include? will be "promoted" to # DPrecision::MINUTE if it has a precision of DPrecision::DAY or # less. # class REDay include TExpr CURRENT=28 NEXT=29 ANY_DATE=PDate.day(2002,8,CURRENT) attr_reader :range, :spans_midnight def initialize(start_hour, start_minute, end_hour, end_minute, less_precise_match=true) start_time = PDate.min(ANY_DATE.year,ANY_DATE.month, ANY_DATE.day,start_hour,start_minute) if(@spans_midnight = spans_midnight?(start_hour, end_hour)) then end_time = get_next(end_hour,end_minute) else end_time = get_current(end_hour,end_minute) end @range = start_time..end_time @less_precise_match = less_precise_match end def ==(o) o.is_a?(REDay) ? spans_midnight == o.spans_midnight && range == o.range : super(o) end def include?(date) # # If @less_precise_match == true and the precision of the argument # is day or greater, then the result is always true return true if @less_precise_match && less_precise?(date) date_to_use = ensure_precision(date) if(@spans_midnight&&date_to_use.hour<12) then #Assume next day return @range.include?(get_next(date_to_use.hour,date_to_use.min)) end #Same day return @range.include?(get_current(date_to_use.hour,date_to_use.min)) end def to_s "from #{Runt.format_time(@range.begin)} to #{Runt.format_time(@range.end)} daily" end private def less_precise?(date) date.date_precision <= DPrecision::DAY end def ensure_precision(date) return date unless less_precise?(date) DPrecision.to_p(date,DPrecision::MIN) end def spans_midnight?(start_hour, end_hour) return end_hour < start_hour end def get_current(hour,minute) PDate.min(ANY_DATE.year,ANY_DATE.month,CURRENT,hour,minute) end def get_next(hour,minute) PDate.min(ANY_DATE.year,ANY_DATE.month,NEXT,hour,minute) end end # TExpr that matches the week in a month. For example: # # WIMonth.new(1) # # See also: Date # FIXME .dates mixin seems functionally broken class WIMonth include TExpr include TExprUtils VALID_RANGE = -2..5 attr_reader :ordinal def initialize(ordinal) unless VALID_RANGE.include?(ordinal) raise ArgumentError, 'invalid ordinal week of month' end @ordinal = ordinal end def ==(o) o.is_a?(WIMonth) ? ordinal == o.ordinal : super(o) end def include?(date) week_matches?(@ordinal,date) end def to_s "#{Runt.ordinalize(@ordinal)} week of any month" end end # TExpr that matches a range of dates within a month. For example: # # REMonth.(12,28) # # matches from the 12th thru the 28th of any month. If end_day==0 # or is not given, start_day will define the range with that single day. # # See also: Date class REMonth include TExpr attr_reader :range def initialize(start_day, end_day=0) end_day=start_day if end_day==0 @range = start_day..end_day end def ==(o) o.is_a?(REMonth) ? range == o.range : super(o) end def include?(date) @range.include? date.mday end def to_s "from the #{Runt.ordinalize(@range.begin)} to the #{Runt.ordinalize(@range.end)} monthly" end end # # Using the precision from the supplied start argument and the its date value, # matches every n number of time units thereafter. # class EveryTE include TExpr attr_reader :start, :interval, :precision def initialize(start,n,precision=nil) @start=start @interval=n # Use the precision of the start date by default @precision=precision || @start.date_precision end def ==(o) o.is_a?(EveryTE) ? start == o.start && precision == o.precision && interval == o.interval : super(o) end def include?(date) i=DPrecision.to_p(@start,@precision) d=DPrecision.to_p(date,@precision) while i<=d return true if i.eql?(d) i=i+@interval end false end def to_s "every #{@interval} #{@precision.label.downcase}s starting #{Runt.format_date(@start)}" end end # Using day precision dates, matches every n number of days after a given # base date. All date arguments are converted to DPrecision::DAY precision. # # Contributed by Ira Burton class DayIntervalTE include TExpr attr_reader :interval, :base_date def initialize(base_date,n) @base_date = DPrecision.to_p(base_date,DPrecision::DAY) @interval = n end def ==(o) o.is_a?(DayIntervalTE) ? base_date == o.base_date && interval == o.interval : super(o) end def include?(date) return ((DPrecision.to_p(date,DPrecision::DAY) - @base_date).to_i % @interval == 0) end def to_s "every #{Runt.ordinalize(@interval)} day after #{Runt.format_date(@base_date)}" end end # # This class creates an expression which matches dates occuring during the weeks # alternating at the given interval begining on the week containing the date # used to create the instance. # # WeekInterval.new(starting_date, interval) # # Weeks are defined as Sunday to Saturday, as opposed to the commercial week # which starts on a Monday. For example, # # every_other_week = WeekInterval.new(Date.new(2013,04,24), 2) # # will match any date that occurs during every other week begining with the # week of 2013-04-21 (2013-04-24 is a Wednesday and 2013-04-21 is the Sunday # that begins the containing week). # # # Sunday of starting week # every_other_week.include?(Date.new(2013,04,21)) #==> true # # Saturday of starting week # every_other_week.include?(Date.new(2013,04,27)) #==> true # # First week _after_ start week # every_other_week.include?(Date.new(2013,05,01)) #==> false # # Second week _after_ start week # every_other_week.include?(Date.new(2013,05,06)) #==> true # # NOTE: The idea and tests for this class were originally contributed as the # REWeekWithIntervalTE class by Jeff Whitmire. The behavior of the original class # provided both the matching of every n weeks and the specification of specific # days of that week in a single class. This class only provides the matching # of every n weeks. The exact functionality of the original class is easy to create # using the Runt set operators and the DIWeek class: # # # Old way # tu_thurs_every_third_week = REWeekWithIntervalTE.new(Date.new(2013,04,24),2,[2,4]) # # # New way # tu_thurs_every_third_week = # WeekInterval.new(Date.new(2013,04,24),2) & (DIWeek.new(Tuesday) | DIWeek.new(Thursday)) # # Notice that the compound expression (in parens after the "&") can be replaced # or combined with any other appropriate temporal expression to provide different # functionality (REWeek to provide a range of days, REDay to provide certain times, etc...). # # Contributed by Jeff Whitmire class WeekInterval include TExpr def initialize(start_date,interval=2) @start_date = DPrecision.to_p(start_date,DPrecision::DAY) # convert base_date to the start of the week @base_date = @start_date - @start_date.wday @interval = interval end def include?(date) return false if @base_date > date ((adjust_for_year(date) - week_num(@base_date)) % @interval) == 0 end def to_s "every #{Runt.ordinalize(@interval)} week starting with the week containing #{Runt.format_date(@start_date)}" end private def week_num(date) # %U - Week number of the year. The week starts with Sunday. (00..53) date.strftime("%U").to_i end def max_week_num(year) d = Date.new(year,12,31) max = week_num(d) while max < 52 d = d - 1 max = week_num(d) end max end def adjust_for_year(date) # Exclusive range: if date.year == @base_date.year, this will be empty range_of_years = @base_date.year...date.year in_same_year = range_of_years.to_a.empty? # Week number of the given date argument week_number = week_num(date) # Default (most common case) date argument is in same year as @base_date # and the week number is also part of the same year. This starting value # is also necessary for the case where they're not in the same year. adjustment = week_number if in_same_year && (week_number < week_num(@base_date)) then # The given date occurs within the same year # but is actually week number 1 of the next year adjustment = adjustment + max_week_num(date.year) elsif !in_same_year then # Date occurs in different year range_of_years.each do |year| # Max week number taking into account we are not using commercial week adjustment = adjustment + max_week_num(year) end end adjustment end end # Simple expression which returns true if the supplied arguments # occur within the given year. # class YearTE include TExpr attr_reader :year def initialize(year) @year = year end def ==(o) o.is_a?(YearTE) ? year == o.year : super(o) end def include?(date) return date.year == @year end def to_s "during the year #{@year}" end end # Matches dates that occur before a given date. class BeforeTE include TExpr attr_reader :date, :inclusive def initialize(date, inclusive=false) @date = date @inclusive = inclusive end def ==(o) o.is_a?(BeforeTE) ? date == o.date && inclusive == o.inclusive : super(o) end def include?(date) return false unless date return (date < @date) || (@inclusive && @date == date) end def to_s "before #{Runt.format_date(@date)}" end end # Matches dates that occur after a given date. class AfterTE include TExpr attr_reader :date, :inclusive def initialize(date, inclusive=false) @date = date @inclusive = inclusive end def ==(o) o.is_a?(AfterTE) ? date == o.date && inclusive == o.inclusive : super(o) end def include?(date) return (date > @date) || (@inclusive && @date == date) end def to_s "after #{Runt.format_date(@date)}" end end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
mlipper/runt
https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/schedule.rb
lib/runt/schedule.rb
#!/usr/bin/env ruby module Runt # Implementation of a <tt>pattern</tt>[http://martinfowler.com/apsupp/recurring.pdf] # for recurring calendar events created by Martin Fowler. class Schedule def initialize @elems = Hash.new self end # Schedule event to occur using the given expression. # NOTE: version 0.5.0 no longer uses an Array of ScheduleElements # internally to hold data. This would only matter to clients if they # they depended on the ability to call add multiple times for the same # event. Use the update method instead. def add(event, expression) @elems[event]=expression end # For the given date range, returns an Array of PDate objects at which # the supplied event is scheduled to occur. def dates(event, date_range) result=[] date_range.each do |date| result.push date if include?(event,date) end result end def scheduled_dates(date_range) @elems.values.collect{|expr| expr.dates(date_range)}.flatten.sort.uniq end # Return true or false depend on if the supplied event is scheduled to occur on the # given date. def include?(event, date) return false unless @elems.include?(event) return 0<(self.select{|ev,xpr| ev.eql?(event)&&xpr.include?(date);}).size end # # Returns all Events whose Temporal Expression includes the given date/expression # def events(date) self.select{|ev,xpr| xpr.include?(date);} end # # Selects events using the user supplied block/Proc. The Proc must accept # two parameters: an Event and a TemporalExpression. It will be called # with each existing Event-expression pair at which point it can choose # to include the Event in the final result by returning true or to filter # it by returning false. # def select(&block) result=[] @elems.each_pair{|event,xpr| result.push(event) if block.call(event,xpr);} result end # # Call the supplied block/Proc with the currently configured # TemporalExpression associated with the supplied Event. # def update(event,&block) block.call(@elems[event]) end def date_to_event_hash(event_attribute=:id) start_date = end_date = nil @elems.keys.each do |event| start_date = event.start_date if start_date.nil? || start_date > event.start_date end_date = event.end_date if end_date.nil? || end_date < event.end_date end scheduled_dates(DateRange.new(start_date, end_date)).inject({}) do |h, date| h[date] = events(date).collect{|e| e.send(event_attribute)} h end end end # TODO: Extend event to take other attributes class Event attr_reader :id def initialize(id) raise Exception, "id argument cannot be nil" unless !id.nil? @id=id end def to_s; @id.to_s end def == (other) return true if other.kind_of?(Event) && @id==other.id end end end
ruby
MIT
d0dab62fa45571e50e2018dbe1e12a9fe2752f61
2026-01-04T17:54:05.922730Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true if ENV["COVERAGE"] == "true" require "simplecov" require "simplecov-console" require "codecov" SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::Console, SimpleCov::Formatter::Codecov, ] SimpleCov.start do track_files "lib/**/*.rb" end puts "Using SimpleCov v#{SimpleCov::VERSION}" end require "byebug" require "minitest/autorun" require "minitest/pride" require "minitest/around/spec" require "minitest-spec-context" require "rails_stats/all"
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/jobs/application_job.rb
test/dummy/app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base # Automatically retry jobs that encountered a deadlock # retry_on ActiveRecord::Deadlocked # Most jobs are safe to ignore if the underlying records are no longer available # discard_on ActiveJob::DeserializationError end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/helpers/application_helper.rb
test/dummy/app/helpers/application_helper.rb
module ApplicationHelper include Pagy::Frontend end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/controllers/application_controller.rb
test/dummy/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base include Pagy::Backend def hello p hello end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/models/pet.rb
test/dummy/app/models/pet.rb
class Pets < User end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/models/comment.rb
test/dummy/app/models/comment.rb
class Comments < ApplicationRecord belongs_to :commentable, polymorphic: true end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/models/application_record.rb
test/dummy/app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/models/user.rb
test/dummy/app/models/user.rb
class Users < ApplicationRecord end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/mailers/application_mailer.rb
test/dummy/app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base default from: 'from@example.com' layout 'mailer' end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/channels/application_cable/channel.rb
test/dummy/app/channels/application_cable/channel.rb
module ApplicationCable class Channel < ActionCable::Channel::Base end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/app/channels/application_cable/connection.rb
test/dummy/app/channels/application_cable/connection.rb
module ApplicationCable class Connection < ActionCable::Connection::Base end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/db/schema.rb
test/dummy/db/schema.rb
ActiveRecord::Schema[7.0].define(version: 2023_04_25_154701) do create_table "users", force: :cascade do |t| t.string "email" end create_table "comments", force: :cascade do |t| t.bigint :commentable_id t.string :commentable_type end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/test/support/test_helper.rb
test/dummy/test/support/test_helper.rb
puts "This is a test support file"
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/test/models/user_test.rb
test/dummy/test/models/user_test.rb
class UserTest end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/spec/support/support_file.rb
test/dummy/spec/support/support_file.rb
puts "This is a spec support file"
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/spec/models/user_spec.rb
test/dummy/spec/models/user_spec.rb
class FooBar end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/lib/monkeypatches.rb
test/dummy/lib/monkeypatches.rb
puts "Monkeypatches go here"
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/application.rb
test/dummy/config/application.rb
require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "active_storage/engine" require "action_controller/railtie" require "action_mailer/railtie" require "action_mailbox/engine" require "action_text/engine" require "action_view/railtie" require "action_cable/engine" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Dummy class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.0 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. # Don't generate system test files. config.generators.system_tests = nil end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/environment.rb
test/dummy/config/environment.rb
# Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/puma.rb
test/dummy/config/puma.rb
# Puma can serve each request in a thread from an internal thread pool. # The `threads` method setting takes two numbers: a minimum and maximum. # Any libraries that use thread pools should be configured to match # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum; this matches the default thread size of Active Record. # max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } threads min_threads_count, max_threads_count # Specifies the `port` that Puma will listen on to receive requests; default is 3000. # port ENV.fetch("PORT") { 3000 } # Specifies the `environment` that Puma will run in. # environment ENV.fetch("RAILS_ENV") { "development" } # Specifies the `pidfile` that Puma will use. pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } # Specifies the number of `workers` to boot in clustered mode. # Workers are forked web server processes. If using threads and workers together # the concurrency of the application would be max `threads` * `workers`. # Workers do not work on JRuby or Windows (both of which do not support # processes). # # workers ENV.fetch("WEB_CONCURRENCY") { 2 } # Use the `preload_app!` method when specifying a `workers` number. # This directive tells Puma to first boot the application and load code # before forking the application. This takes advantage of Copy On Write # process behavior so workers use less memory. # # preload_app! # Allow puma to be restarted by `rails restart` command. plugin :tmp_restart
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/routes.rb
test/dummy/config/routes.rb
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/spring.rb
test/dummy/config/spring.rb
Spring.watch( ".ruby-version", ".rbenv-vars", "tmp/restart.txt", "tmp/caching-dev.txt" )
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/boot.rb
test/dummy/config/boot.rb
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' # Set up gems listed in the Gemfile. require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/content_security_policy.rb
test/dummy/config/initializers/content_security_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide content security policy # For further information see the following documentation # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy # Rails.application.config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # If you are using webpack-dev-server then specify webpack-dev-server host # policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # If you are using UJS then enable automatic nonce generation # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } # Set the nonce only to specific directives # Rails.application.config.content_security_policy_nonce_directives = %w(script-src) # Report CSP violations to a specified URI # For further information see the following documentation: # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only # Rails.application.config.content_security_policy_report_only = true
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/filter_parameter_logging.rb
test/dummy/config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/application_controller_renderer.rb
test/dummy/config/initializers/application_controller_renderer.rb
# Be sure to restart your server when you modify this file. # ActiveSupport::Reloader.to_prepare do # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # ) # end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false