module Quandl module Cassinatra module Model class Dataset module Searchable extend ActiveSupport::Concern module ClassMethods def valid_transformation?(type) valid_transformations.include?( type ) end def valid_transformations [ :diff, :rdiff, :cumul, :normalize ] end def search_scopes @search_scopes ||+ search_scope.scopes.keys end end included do include Quandl include ScopeBuilder::Model scope_builder_for :search search_helper :column_ids, -> { dataset.column_ids } search_helper :data_table, -> { dataset.data_table } search_helper :dataset, -> { find(attributes[:id]) } search_scope.class_eval do delegate *Array.forwardable_methods, to: :data_table delegate *Data::Table.forwardable_methods, to: :data_table end search_scope :limit, ->(amount) { where( limit: amount.to_i ) } search_scope :column, ->(index) { where( column: index.to_i ) } search_scope :order, ->(dir) { where( order: (dir.to_sym == :asc) ? 'asc' : 'desc' ) } search_scope :trim_start, ->(date) { where( trim_start: format_trim_date(date, :start)) } search_scope :trim_end, ->(date) { where( trim_end: format_trim_date(date, :end)) } search_scope :transform, ->(value) { where( transform: value ) if self.class.parent.valid_transformation?(value) } search_scope :with_id, ->(value) { where( id: value.to_i )} search_scope :collapse, ->(name){ # set collapse where( collapse: name ) # reset trims to force them to edge of frequency trim_start(trim_start) if trim_start trim_end(trim_end) if trim_end } search_helper :format_trim_date, ->( date, start_or_end ){ date = Date.jd(date) if date.is_a?(Integer) date = Date.parse(date) if date.is_a?(String) date = date.send("#{start_or_end}_of_frequency", collapse) if collapse.present? date.jd } search_helper :find, ->(id){ begin t1 = Time.now result = self.class.parent.where(attributes).find(id) puts "parent.where(#{attributes.to_param if attributes.respond_to?(:to_param)}).find(#{id}) (#{t1.elapsed_ms})" rescue => error puts "ERROR: Cassandra #{error}" end result = self.class.parent.new(id: id) if result.nil? result } end end end end end end