repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
ryanlntn/medic
lib/medic/units.rb
module Medic module Units def sample_unit(u) return unless u camelized = u.to_s.gsub(/_([a-z]*)/){ "#{$1.capitalize}" } if HKUnit.respond_to?(:"#{camelized}Unit") HKUnit.send(:"#{camelized}Unit") else HKUnit.unitFromString(u.to_s) end end end end
ryanlntn/medic
lib/medic/observer_query_builder.rb
module Medic class ObserverQueryBuilder attr_reader :params attr_reader :query include Medic::Types include Medic::Predicate def initialize(args={}, block=Proc.new) @params = args @query = HKObserverQuery.alloc.initWithSampleType(object_type(args[:type]), predicate: predicate(args), updateHandler: block ) end end end
ryanlntn/medic
lib/medic/statistics_collection_query_builder.rb
module Medic class StatisticsCollectionQueryBuilder attr_reader :params attr_reader :query include Medic::Types include Medic::Predicate include Medic::StatisticsOptions include Medic::Anchor include Medic::Interval def initialize(args={}) @params = args @query = HKStatisticsCollectionQuery.alloc.initWithQuantityType(object_type(args[:type]), quantitySamplePredicate: predicate(args), options: options_for_stat_query(args[:options]), anchorDate: anchor_for_symbol(args[:anchor_date] || args[:anchor] || args[:date] || NSDate.date), intervalComponents: interval(args[:interval_components] || args[:interval]) ) if block_given? handler = Proc.new @query.initialResultsHandler = handler @query.statisticsUpdateHandler = Proc.new{|q,_,r,e| handler.call(q,r,e)} if args[:update] == true end @query.statisticsUpdateHandler = args[:update] if args[:update].is_a?(Proc) end def initial_results_handler @query.initialResultsHandler end def initial_results_handler=(callback=Proc.new) @query.initialResultsHandler = callback end def statistics_update_handler @query.statisticsUpdateHandler end def statistics_update_handler=(callback=Proc.new) @query.statisticsUpdateHandler = callback end end end
ryanlntn/medic
lib/medic/correlation_query_builder.rb
<reponame>ryanlntn/medic module Medic class CorrelationQueryBuilder attr_reader :params attr_reader :query include Medic::Types include Medic::Predicate def initialize(args={}, block=Proc.new) @params = args @query = HKCorrelationQuery.alloc.initWithType(object_type(args[:type]), predicate: predicate(args), samplePredicates: sample_predicates(args[:sample_predicates]), completion: block ) end private def sample_predicates(predicates) Hash[ predicates.map{ |type, pred| [object_type(type), predicate(pred)] } ] end end end
ryanlntn/medic
lib/medic/finders.rb
<gh_stars>10-100 module Medic module Finders def observe(type, options={}, block=Proc.new) query_params = options.merge(type: type) query = Medic::ObserverQueryBuilder.new query_params do |query, completion, error| block.call(completion, error) end.query Medic.execute(query) end def find_sources(type, options={}, block=Proc.new) query_params = options.merge(type: type) query = Medic::SourceQueryBuilder.new query_params do |query, results, error| sources = results ? results.allObjects.map{ |source| source.name.to_s } : [] block.call(sources) end.query Medic.execute(query) end def find_samples(type, options={}, block=Proc.new) query_params = options.merge(type: type) query = Medic::SampleQueryBuilder.new query_params do |query, results, error| block.call(samples_to_hashes(Array(results))) end.query Medic.execute(query) end def find_correlations(type, options={}, block=Proc.new) query_params = options.merge(type: type) query = Medic::CorrelationQueryBuilder.new query_params do |query, correlations, error| block.call(samples_to_hashes(Array(correlations))) end.query Medic.execute(query) end def find_anchored(type, options={}, block=Proc.new) query_params = options.merge(type: type) query = Medic::AnchoredObjectQueryBuilder.new query_params do |query, results, new_anchor, error| block.call(samples_to_hashes(Array(results)), new_anchor) end.query Medic.execute(query) end def find_statistics(type, options={}, block=Proc.new) query_params = options.merge(type: type) query = Medic::StatisticsQueryBuilder.new query_params do |query, statistics, error| block.call(statistics_to_hash(statistics)) if statistics end.query Medic.execute(query) end def find_statistics_collection(type, options={}, block=Proc.new) query_params = options.merge(type: type) query = Medic::StatisticsCollectionQueryBuilder.new query_params do |query, collection, error| from_date = options[:from_date] || options[:from] || options[:start_date] || collection.anchorDate to_date = options[:to_date] || options[:to] || options[:end_date] || NSDate.date formatted_stats = [] if collection collection.enumerateStatisticsFromDate(from_date, toDate: to_date, withBlock: ->(result, stop){ formatted_stats << statistics_to_hash(result) }) end block.call(formatted_stats) end.query Medic.execute(query) end private def samples_to_hashes(samples) samples.map do |sample| h = {} h[:uuid] = sample.UUID.UUIDString h[:metadata] = sample.metadata h[:source] = sample.source.name h[:start_date] = sample.startDate h[:end_date] = sample.endDate h[:sample_type] = Medic::Types::TYPE_IDENTIFIERS.key(sample.sampleType.identifier) if sample.respond_to?(:categoryType) && sample.respond_to?(:value) h[:category_type] = Medic::Types::TYPE_IDENTIFIERS.key(sample.categoryType.identifier) h[:value] = [:in_bed, :asleep][sample.value] # SleepAnalysis is the only category type at the moment end if sample.respond_to?(:correlationType) && sample.respond_to?(:objects) h[:correlation_type] = Medic::Types::TYPE_IDENTIFIERS.key(sample.correlationType.identifier) h[:objects] = samples_to_hashes(Array(sample.objects.allObjects)) end if sample.respond_to?(:quantity) && sample.respond_to?(:quantityType) h[:quantity] = sample.quantity.doubleValueForUnit(sample.quantityType.canonicalUnit) h[:quantity_type] = Medic::Types::TYPE_IDENTIFIERS.key(sample.quantityType.identifier) h[:canonical_unit] = sample.quantityType.canonicalUnit.unitString end h[:duration] = sample.duration if sample.respond_to?(:duration) h[:total_distance] = sample.totalDistance if sample.respond_to?(:totalDistance) h[:total_energy_burned] = sample.totalEnergyBurned if sample.respond_to?(:totalEnergyBurned) h[:workout_activity_type] = sample.workoutActivityType if sample.respond_to?(:workoutActivityType) h[:workout_events] = sample.workoutEvents if sample.respond_to?(:workoutEvents) h end end def statistics_to_hash(stats) h = {} h[:start_date] = stats.startDate h[:end_date] = stats.endDate h[:sources] = stats.sources.map(&:name) if stats.sources h[:quantity_type] = Medic::Types::TYPE_IDENTIFIERS.key(stats.quantityType.identifier) h[:canonical_unit] = stats.quantityType.canonicalUnit.unitString h[:data_count] = stats.dataCount h[:average] = stats.averageQuantity.doubleValueForUnit(stats.quantityType.canonicalUnit) if stats.averageQuantity h[:minimum] = stats.minimumQuantity.doubleValueForUnit(stats.quantityType.canonicalUnit) if stats.minimumQuantity h[:maximum] = stats.maximumQuantity.doubleValueForUnit(stats.quantityType.canonicalUnit) if stats.maximumQuantity h[:sum] = stats.sumQuantity.doubleValueForUnit(stats.quantityType.canonicalUnit) if stats.sumQuantity h[:average_by_source] = stats.averageQuantityBySource.doubleValueForUnit(stats.quantityType.canonicalUnit) if stats.averageQuantityBySource h[:minimum_by_source] = stats.minimumQuantityBySource.doubleValueForUnit(stats.quantityType.canonicalUnit) if stats.minimumQuantityBySource h[:maximum_by_source] = stats.maximumQuantityBySource.doubleValueForUnit(stats.quantityType.canonicalUnit) if stats.maximumQuantityBySource h[:sum_by_source] = stats.sumQuantityBySource.doubleValueForUnit(stats.quantityType.canonicalUnit) if stats.sumQuantityBySource h end end end
ryanlntn/medic
spec/medic/sample_query_builder_spec.rb
describe Medic::SampleQueryBuilder do before do @subject = Medic::SampleQueryBuilder.new type: :dietary_protein, limit: 7 do |query, results, error| end end it "has a query getter that returns an HKSampleQuery" do @subject.query.should.be.kind_of? HKSampleQuery end end
ryanlntn/medic
spec/medic/hk_constants_spec.rb
describe Medic::HKConstants do before do @subject = Object.new @subject.extend(Medic::HKConstants) end describe "#error_code" do it "returns the correct error code for symbol" do @subject.error_code(:no_error).should == HKNoError @subject.error_code(:health_data_unavailable).should == HKErrorHealthDataUnavailable @subject.error_code(:health_data_restricted).should == HKErrorHealthDataRestricted @subject.error_code(:invalid_argument).should == HKErrorInvalidArgument @subject.error_code(:authorization_denied).should == HKErrorAuthorizationDenied @subject.error_code(:authorization_not_determined).should == HKErrorAuthorizationNotDetermined @subject.error_code(:database_inaccessible).should == HKErrorDatabaseInaccessible @subject.error_code(:user_canceled).should == HKErrorUserCanceled end end describe "#update_frequency" do it "returns the correct update frequency for symbol" do @subject.update_frequency(:immediate).should == HKUpdateFrequencyImmediate @subject.update_frequency(:hourly).should == HKUpdateFrequencyHourly @subject.update_frequency(:daily).should == HKUpdateFrequencyDaily @subject.update_frequency(:weekly).should == HKUpdateFrequencyWeekly end end describe "#authorization_status" do it "returns the correct authorization status for symbol" do @subject.authorization_status(:not_determined).should == HKAuthorizationStatusNotDetermined @subject.authorization_status(:sharing_denied).should == HKAuthorizationStatusSharingDenied @subject.authorization_status(:sharing_authorized).should == HKAuthorizationStatusSharingAuthorized end end describe "#biological_sex" do it "returns the correct biological sex for symbol" do @subject.biological_sex(:not_set).should == HKBiologicalSexNotSet @subject.biological_sex(:female).should == HKBiologicalSexFemale @subject.biological_sex(:male).should == HKBiologicalSexMale end end describe "#blood_type" do it "returns the correct blood type for symbol" do @subject.blood_type(:not_set).should == HKBloodTypeNotSet @subject.blood_type(:a_positive).should == HKBloodTypeAPositive @subject.blood_type(:a_negative).should == HKBloodTypeANegative @subject.blood_type(:b_positive).should == HKBloodTypeBPositive @subject.blood_type(:b_negative).should == HKBloodTypeBNegative @subject.blood_type(:a_b_positive).should == HKBloodTypeABPositive @subject.blood_type(:a_b_negative).should == HKBloodTypeABNegative @subject.blood_type(:o_positive).should == HKBloodTypeOPositive @subject.blood_type(:o_negative).should == HKBloodTypeONegative end end describe "#sleep_analysis" do it "returns the correct sleep analysis for symbol" do @subject.sleep_analysis(:in_bed).should == HKCategoryValueSleepAnalysisInBed @subject.sleep_analysis(:asleep).should == HKCategoryValueSleepAnalysisAsleep end end end
ryanlntn/medic
spec/medic/interval_spec.rb
<filename>spec/medic/interval_spec.rb describe Medic::Interval do before do @subject = Object.new @subject.extend(Medic::Interval) end describe "#interval" do it "returns the correct NSDateComponents object for symbol" do @subject.interval(:nine_hundred_ninety_nine_days).should.be.kind_of? NSDateComponents @subject.interval(:nine_hundred_ninety_nine_days).day.should == 999 @subject.interval("365 days").day.should == 365 @subject.interval(:day).day.should == 1 end end end
ryanlntn/medic
lib/medic/anchor.rb
module Medic module Anchor NUMBER_WORDS = { 'zero' => 0, 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5, 'six' => 6, 'seven' => 7, 'eight' => 8, 'nine' => 9, 'ten' => 10, 'eleven' => 11, 'twelve' => 12, 'thirteen' => 13, 'fourteen' => 14, 'fifteen' => 15, 'sixteen' => 16, 'seventeen' => 17, 'eighteen' => 18, 'nineteen' => 19, 'twenty' => 20, 'thirty' => 30, 'fourty' => 40, 'fifty' => 50, 'sixty' => 60, 'seventy' => 70, 'eighty' => 80, 'ninety' => 90, 'hundred' => 100 } def anchor_for_symbol(sym) return unless sym return sym if sym.to_s == '0' return sym if sym.is_a? Fixnum return sym if sym.is_a? NSDate parts = sym.to_s.gsub('_', ' ').split.reject{ |part| part == 'ago' } component = parts.pop.chomp('s') n = parts.map{|p| NUMBER_WORDS[p] || p.to_i}.reduce do |sum, p| if p == 100 && sum > 0 sum * p else sum + p end end n ||= 1 date_comp = NSDateComponents.new.send("#{component}=", -n) NSCalendar.currentCalendar.dateByAddingComponents(date_comp, toDate: NSDate.date, options: 0) end end end
ryanlntn/medic
lib/medic/store.rb
module Medic class Store include Medic::Types include Medic::Units include Medic::HKConstants def self.shared Dispatch.once { @@hk_store ||= HKHealthStore.new } Dispatch.once { @medic_store ||= new } @medic_store end def self.hk_store @@hk_store end def self.unload @@hk_store = nil @medic_store = nil end def self.available? HKHealthStore.isHealthDataAvailable end singleton_class.send(:alias_method, :is_available?, :available?) def authorize(types, block=Proc.new) share = Array(types[:share] || types[:write]).map{ |sym| object_type(sym) } read = Array(types[:read]).map{ |sym| object_type(sym) } @@hk_store.requestAuthorizationToShareTypes(NSSet.setWithArray(share), readTypes: NSSet.setWithArray(read), completion: ->(success, error){ block.call(success, error) }) end def authorized?(sym) @@hk_store.authorizationStatusForType(object_type(sym)) == HKAuthorizationStatusSharingAuthorized end alias_method :authorized_for?, :authorized? alias_method :is_authorized?, :authorized? alias_method :is_authorized_for?, :authorized? def biological_sex error = Pointer.new(:object) sex = @@hk_store.biologicalSexWithError error if block_given? yield BIOLOGICAL_SEXES.invert[sex.biologicalSex], error[0] else BIOLOGICAL_SEXES.invert[sex.biologicalSex] end end def blood_type error = Pointer.new(:object) blood = @@hk_store.bloodTypeWithError error if block_given? yield BLOOD_TYPES.invert[blood.bloodType], error[0] else BLOOD_TYPES.invert[blood.bloodType] end end def date_of_birth error = Pointer.new(:object) birthday = @@hk_store.dateOfBirthWithError error if block_given? yield birthday, error[0] else birthday end end def delete(hk_object, block=Proc.new) @@hk_store.deleteObject(hk_object, withCompletion: ->(success, error){ block.call(success, error) }) end alias_method :delete_object, :delete def save(hk_objects, block=Proc.new) objs_array = hk_objects.is_a?(Array) ? hk_objects : [hk_objects] @@hk_store.saveObjects(objs_array.map{|obj| prepare_for_save(obj)}, withCompletion: ->(success, error){ block.call(success, error) }) end alias_method :save_object, :save alias_method :save_objects, :save # TODO: workout support # addSamples:toWorkout:completion: def execute(query) @@hk_store.executeQuery(query) end alias_method :execute_query, :execute def stop(query) @@hk_store.stopQuery(query) end alias_method :stop_query, :stop def enable_background_delivery(type, frequency, block=Proc.new) @@hk_store.enableBackgroundDeliveryForType(object_type(type), frequency: update_frequency(frequency), withCompletion: ->(success, error){ block.call(success, error) }) end alias_method :enable_background_delivery_for, :enable_background_delivery def disable_background_delivery(type, block=Proc.new) return disable_all_background_delivery(block) if type == :all @@hk_store.disableBackgroundDeliveryForType(object_type(type), withCompletion: ->(success, error){ block.call(success, error) }) end alias_method :disable_background_delivery_for, :disable_background_delivery def disable_all_background_delivery(block=Proc.new) @@hk_store.disableAllBackgroundDeliveryWithCompletion(->(success, error){ block.call(success, error) }) end private def prepare_for_save(sample) return sample if sample.kind_of? HKSample date = sample[:date] || NSDate.date start_date = sample[:start] || sample[:start_date] || date end_date = sample[:end] || sample[:end_date] || date metadata = sample[:metadata] || {} type = object_type(sample[:type] || sample[:sample_type] || sample[:quantity_type] || sample[:correlation_type] || sample[:category_type]) case type when HKQuantityType quantity = HKQuantity.quantityWithUnit((sample_unit(sample[:unit]) || type.canonicalUnit), doubleValue: sample[:quantity]) HKQuantitySample.quantitySampleWithType(type, quantity: quantity, startDate: start_date, endDate: end_date, metadata: metadata) when HKCorrelationType objects = (sample[:objects].is_a?(Array) ? sample[:objects] : [sample[:objects]]).map{|obj| prepare_for_save(obj)} HKCorrelation.correlationWithType(type, startDate: start_date, endDate: end_date, objects: objects, metadata: metadata) when HKCategoryType value = sleep_analysis(sample[:value]) # SleepAnalysis is the only category type at the moment HKCategorySample.categorySampleWithType(type, value: value, startDate: start_date, endDate: end_date, metadata: metadata) else # handle workouts end end end end
ryanlntn/medic
spec/medic/correlation_query_builder_spec.rb
describe Medic::CorrelationQueryBuilder do before do high_cal = HKQuantity.quantityWithUnit(HKUnit.kilocalorieUnit, doubleValue: 800.0) greater_than_high_cal = HKQuery.predicateForQuantitySamplesWithOperatorType(NSGreaterThanOrEqualToPredicateOperatorType, quantity: high_cal) energy_consumed = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed) sample_predicates = { energy_consumed => greater_than_high_cal } @subject = Medic::CorrelationQueryBuilder.new type: :food, sample_predicates: sample_predicates do |query, correlations, error| end end it "has a query getter that returns an HKCorrelationQuery" do @subject.query.should.be.kind_of? HKCorrelationQuery end end
ryanlntn/medic
spec/medic/statistics_query_builder_spec.rb
describe Medic::StatisticsQueryBuilder do before do @subject = Medic::StatisticsQueryBuilder.new type: :step_count, options: :sum do |query, results, error| end end it "has a query getter that returns an HKStatisticsQuery" do @subject.query.should.be.kind_of? HKStatisticsQuery end end
ryanlntn/medic
lib/medic/source_query_builder.rb
module Medic class SourceQueryBuilder attr_reader :params attr_reader :query include Medic::Types include Medic::Predicate def initialize(args={}, block=Proc.new) @params = args @query = HKSourceQuery.alloc.initWithSampleType(object_type(args[:type]), samplePredicate: predicate(args), completionHandler: block ) end end end
ryanlntn/medic
spec/medic/anchored_object_query_builder_spec.rb
<filename>spec/medic/anchored_object_query_builder_spec.rb describe Medic::AnchoredObjectQueryBuilder do before do @subject = Medic::AnchoredObjectQueryBuilder.new type: :step_count do |query, results, new_anchor, error| end end it "has a query getter that returns an HKAnchoredObjectQuery" do @subject.query.should.be.kind_of? HKAnchoredObjectQuery end end
ryanlntn/medic
lib/medic/statistics_query_builder.rb
module Medic class StatisticsQueryBuilder attr_reader :params attr_reader :query include Medic::Types include Medic::Predicate include Medic::StatisticsOptions def initialize(args={}, block=Proc.new) @params = args @query = HKStatisticsQuery.alloc.initWithQuantityType(object_type(args[:type]), quantitySamplePredicate: predicate(args), options: options_for_stat_query(args[:options]), completionHandler: block ) end end end
ryanlntn/medic
spec/medic/observer_query_builder_spec.rb
describe Medic::ObserverQueryBuilder do before do @subject = Medic::ObserverQueryBuilder.new type: :step_count do |query, completion, error| end end it "has a query getter that returns an HKObserverQuery" do @subject.query.should.be.kind_of? HKObserverQuery end end
ryanlntn/medic
lib/medic/anchored_object_query_builder.rb
module Medic class AnchoredObjectQueryBuilder attr_reader :params attr_reader :query include Medic::Types include Medic::Predicate include Medic::Anchor def initialize(args={}, block=Proc.new) @params = args @query = HKAnchoredObjectQuery.alloc.initWithType(object_type(args[:type]), predicate: predicate(args), anchor: anchor_for_symbol(args[:anchor_date] || args[:anchor] || args[:date] || HKAnchoredObjectQueryNoAnchor), limit: args[:limit] || HKObjectQueryNoLimit, completionHandler: block ) end end end
whiteleaf7/enumerize
lib/enumerize/version.rb
<filename>lib/enumerize/version.rb # frozen_string_literal: true module Enumerize VERSION = '2.3.1' end
whiteleaf7/enumerize
lib/enumerize/value.rb
<filename>lib/enumerize/value.rb # frozen_string_literal: true require 'i18n' module Enumerize class Value < String include Predicatable attr_reader :value def initialize(attr, name, value=nil) if self.class.method_defined?("#{name}?") warn("It's not recommended to use `#{name}` as a field value since `#{name}?` is defined. (#{attr.klass.name}##{attr.name})") end @attr = attr @value = value.nil? ? name.to_s : value super(name.to_s) @i18n_keys = @attr.i18n_scopes.map { |s| :"#{s}.#{self}" } @i18n_keys << :"enumerize.defaults.#{@attr.name}.#{self}" @i18n_keys << :"enumerize.#{@attr.name}.#{self}" @i18n_keys << self.underscore.humanize # humanize value if there are no translations @i18n_keys end def text I18n.t(@i18n_keys[0], :default => @i18n_keys[1..-1]) if @i18n_keys end def ==(other) super(other.to_s) || value == other end def encode_with(coder) coder.represent_object(self.class.superclass, @value) end private def predicate_call(value) value == self end end end
hhvm/homebrew-hhvm
Formula/hhvm-4.101.rb
# # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class Hhvm4101 < Formula desc "JIT compiler and runtime for the Hack language" homepage "http://hhvm.com/" head "https://github.com/facebook/hhvm.git" url "https://dl.hhvm.com/source/hhvm-4.101.1.tar.gz" sha256 "5557575d7adac4c2d298506fbb9dc8cb9218165c183dd114b3b1118a4456c8ee" bottle do root_url "https://dl.hhvm.com/homebrew-bottles" sha256 catalina: "51184ed34456f089baa069f328567622734042453e891a1ec74a8c902918958f" end option "with-debug", <<~EOS Make an unoptimized build with assertions enabled. This will run PHP and Hack code dramatically slower than a release build, and is suitable mostly for debugging HHVM itself. EOS # Needs very recent xcode depends_on :macos => :sierra depends_on "autoconf" => :build depends_on "automake" => :build depends_on "cmake" => :build depends_on "dwarfutils" => :build depends_on "gawk" => :build depends_on "libelf" => :build depends_on "libtool" => :build depends_on "md5sha1sum" => :build depends_on "pkg-config" => :build depends_on "wget" => :build # We statically link against icu4c as every non-bugfix release is not # backwards compatible; needing to rebuild for every release is too # brittle depends_on "icu4c" => :build depends_on "boost" depends_on "double-conversion" :xa depends_on "freetype" depends_on "gd" depends_on "gettext" depends_on "glog" depends_on "gmp" depends_on "imagemagick@6" depends_on "jemalloc" depends_on "jpeg" depends_on "libevent" depends_on "libmemcached" depends_on "libsodium" depends_on "libpng" depends_on "libxml2" depends_on "libzip" depends_on "lz4" depends_on "mcrypt" depends_on "oniguruma" depends_on "openssl@1.1" depends_on "pcre" # Used for Hack but not HHVM build - see #116 depends_on "postgresql" depends_on "sqlite" depends_on "tbb@2020" depends_on "zstd" def install cmake_args = std_cmake_args + %W[ -DCMAKE_INSTALL_SYSCONFDIR=#{etc} -DDEFAULT_CONFIG_DIR=#{etc}/hhvm ] # Force use of bundled PCRE to workaround #116 cmake_args += %W[ -DSYSTEM_PCRE_HAS_JIT=0 ] # Features which don't work on OS X yet since they haven't been ported yet. cmake_args += %W[ -DENABLE_MCROUTER=OFF -DENABLE_EXTENSION_MCROUTER=OFF -DENABLE_EXTENSION_IMAP=OFF ] # Required to specify a socket path if you are using the bundled async SQL # client (which is very strongly recommended). cmake_args << "-DMYSQL_UNIX_SOCK_ADDR=/tmp/mysql.sock" # LZ4 warning macros are currently incompatible with clang cmake_args << "-DCMAKE_C_FLAGS=-DLZ4_DISABLE_DEPRECATE_WARNINGS=1" cmake_args << "-DCMAKE_CXX_FLAGS=-DLZ4_DISABLE_DEPRECATE_WARNINGS=1 -DU_USING_ICU_NAMESPACE=1" # Debug builds. This switch is all that's needed, it sets all the right # cflags and other config changes. if build.with? "debug" cmake_args << "-DCMAKE_BUILD_TYPE=Debug" else cmake_args << "-DCMAKE_BUILD_TYPE=RelWithDebInfo" end # Statically link libICU cmake_args += %W[ -DICU_INCLUDE_DIR=#{Formula["icu4c"].opt_include} -DICU_I18N_LIBRARY=#{Formula["icu4c"].opt_lib}/libicui18n.a -DICU_LIBRARY=#{Formula["icu4c"].opt_lib}/libicuuc.a -DICU_DATA_LIBRARY=#{Formula["icu4c"].opt_lib}/libicudata.a ] # TBB looks for itself in a different place than brew installs to. ENV["TBB_ARCH_PLATFORM"] = "." cmake_args += %W[ -DTBB_INCLUDE_DIR=#{Formula["tbb@2020"].opt_include} -DTBB_INSTALL_DIR=#{Formula["tbb@2020"].opt_prefix} -DTBB_LIBRARY=#{Formula["tbb@2020"].opt_lib}/libtbb.dylib -DTBB_LIBRARY_DEBUG=#{Formula["tbb@2020"].opt_lib}/libtbb.dylib -DTBB_LIBRARY_DIR=#{Formula["tbb@2020"].opt_lib} -DTBB_MALLOC_LIBRARY=#{Formula["tbb@2020"].opt_lib}/libtbbmalloc.dylib -DTBB_MALLOC_LIBRARY_DEBUG=#{Formula["tbb@2020"].opt_lib}/libtbbmalloc.dylib ] system "cmake", *cmake_args, '.' system "make" system "make", "install" tp_notices = (share/"doc/third_party_notices.txt") (share/"doc").install "third-party/third_party_notices.txt" (share/"doc/third_party_notices.txt").append_lines <<EOF ----- The following software may be included in this product: icu4c. This Software contains the following license and notice below: Unicode Data Files include all data files under the directories http://www.unicode.org/Public/, http://www.unicode.org/reports/, http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and http://www.unicode.org/utility/trac/browser/. Unicode Data Files do not include PDF online code charts under the directory http://www.unicode.org/Public/. Software includes any source code published in the Unicode Standard or under the directories http://www.unicode.org/Public/, http://www.unicode.org/reports/, http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and http://www.unicode.org/utility/trac/browser/. NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. COPYRIGHT AND PERMISSION NOTICE Copyright © 1991-2017 Unicode, Inc. All rights reserved. Distributed under the Terms of Use in http://www.unicode.org/copyright.html. Permission is hereby granted, free of charge, to any person obtaining a copy of the Unicode data files and any associated documentation (the "Data Files") or Unicode software and any associated documentation (the "Software") to deal in the Data Files or Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Data Files or Software, and to permit persons to whom the Data Files or Software are furnished to do so, provided that either (a) this copyright and permission notice appear with all copies of the Data Files or Software, or (b) this copyright and permission notice appear in associated Documentation. THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in these Data Files or Software without prior written authorization of the copyright holder. EOF ini = etc/"hhvm" (ini/"php.ini").write php_ini unless File.exist? (ini/"php.ini") (ini/"server.ini").write server_ini unless File.exist? (ini/"server.ini") end test do (testpath/"test.php").write <<~EOS <?php exit(is_integer(HHVM_VERSION_ID) ? 0 : 1); EOS system "#{bin}/hhvm", testpath/"test.php" end plist_options :manual => "hhvm -m daemon -c #{HOMEBREW_PREFIX}/etc/hhvm/php.ini -c #{HOMEBREW_PREFIX}/etc/hhvm/server.ini" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> <key>ProgramArguments</key> <array> <string>#{opt_bin}/hhvm</string> <string>-m</string> <string>server</string> <string>-c</string> <string>#{etc}/hhvm/php.ini</string> <string>-c</string> <string>#{etc}/hhvm/server.ini</string> </array> <key>WorkingDirectory</key> <string>#{HOMEBREW_PREFIX}</string> </dict> </plist> EOS end # https://github.com/hhvm/packaging/blob/master/hhvm/deb/skeleton/etc/hhvm/php.ini def php_ini <<~EOS ; php options session.save_handler = files session.save_path = #{var}/lib/hhvm/sessions session.gc_maxlifetime = 1440 ; hhvm specific hhvm.log.always_log_unhandled_exceptions = true hhvm.log.runtime_error_reporting_level = 8191 hhvm.mysql.typed_results = false EOS end # https://github.com/hhvm/packaging/blob/master/hhvm/deb/skeleton/etc/hhvm/server.ini def server_ini <<~EOS ; php options pid = #{var}/run/hhvm/pid ; hhvm specific hhvm.server.port = 9000 hhvm.server.default_document = index.php hhvm.log.use_log_file = true hhvm.log.file = #{var}/log/hhvm/error.log hhvm.repo.central.path = #{var}/run/hhvm/hhvm.hhbc EOS end end
bnadlerjr/gitscore
app/adapters/github.rb
<reponame>bnadlerjr/gitscore<filename>app/adapters/github.rb module Gitscore module Adapters class Github def fetch_profile(username) response = HTTParty.get("http://github.com/#{username}.json") data = JSON.parse(response.body) profile = UserProfile.new( username: data[0]["actor"], name: data[0]["actor_attributes"]["name"] ) data.each do |item| profile.events << Event.new(type: item["type"]) end profile end end end end
bnadlerjr/gitscore
test/unit/user_profile_test.rb
require_relative "../test_helper" require_relative "../../app/user_profile" require_relative "../../app/event" module Gitscore class UserProfileTest < Test::Unit::TestCase test "has events" do profile = UserProfile.new event = Event.new(type: "WatchEvent") profile.events << event assert_equal([event], profile.events) end test "calculate score" do profile = UserProfile.new profile.events << Event.new(type: "WatchEvent") profile.events << Event.new(type: "IssueEvent") assert_equal(4, profile.score) end end end
bnadlerjr/gitscore
test/unit/event_test.rb
<filename>test/unit/event_test.rb require_relative "../test_helper" require_relative "../../app/event" module Gitscore class EventTest < Test::Unit::TestCase test "assigns a score" do event = Event.new(type: "WatchEvent") assert_equal(1, event.score) end test "assign a score of zero for unknown event" do event = Event.new(type: "UnknownEvent") assert_equal(0, event.score) end end end
bnadlerjr/gitscore
app/user_profile.rb
<filename>app/user_profile.rb module Gitscore UserProfile = Struct.new(:username, :name, :events) do def initialize(**attrs) attrs.each { |k, v| self[k] = v } self[:events] = [] end def score self.events.reduce(0) { |sum, e| sum + e.score } end end end
bnadlerjr/gitscore
test/integration/github_test.rb
require_relative "../test_helper" require_relative "../../app/adapters/github" require_relative "../../app/user_profile" require_relative "../../app/event" require "httparty" module Gitscore module Adapters class GithubTest < Test::Unit::TestCase test "fetch profile" do github = Github.new profile = github.fetch_profile("bnadlerjr") assert_equal("bnadlerjr", profile.username) assert_equal("<NAME>", profile.name) assert_equal(30, profile.events.count) end end end end
bnadlerjr/gitscore
app.rb
require "sinatra/base" require "rack/csrf" require_relative "app/adapters/github" require_relative "app/user_profile" require_relative "app/event" require "httparty" Dir.glob(File.join("helpers", "**", "*.rb")).each do |helper| require_relative helper end module Gitscore class App < Sinatra::Base set :root, File.dirname(__FILE__) enable :logging use Rack::Session::Cookie, :secret => "TODO: CHANGE ME" use Rack::Csrf, :raise => true configure :development do require "sinatra/reloader" register Sinatra::Reloader end get "/" do erb :index end get "/:username" do @profile = settings.github.fetch_profile(params[:username]) erb :profile end end end
bnadlerjr/gitscore
test/unit/app_test.rb
require_relative "../test_helper" require_relative "../../app/user_profile" require_relative "../../app/event" class FakeGithub def fetch_profile(username) profile = Gitscore::UserProfile.new( username: "bnadlerjr", name: "<NAME>" ) profile.events << Gitscore::Event.new(type: "WatchEvent") profile.events << Gitscore::Event.new(type: "IssueEvent") profile end end class AppTest < Rack::Test::TestCase test "GET /" do get "/" assert_response :ok end test "GET username" do app.set :github, FakeGithub.new get "/bnadlerjr" assert_response :ok assert_body_contains "bnadlerjr" assert_body_contains "<NAME>" assert_body_contains "Score: 4" end end
bnadlerjr/gitscore
config.ru
<reponame>bnadlerjr/gitscore<gh_stars>1-10 require "bundler/setup" require "dotenv" Dotenv.load require File.expand_path("../app", __FILE__) app = Gitscore::App app.set :github, Gitscore::Adapters::Github.new run app
bnadlerjr/gitscore
app/event.rb
module Gitscore SCORES = { "CommitCommentEvent" => 2, "IssueCommentEvent" => 2, "IssueEvent" => 3, "WatchEvent" => 1, "PullRequestEvent" => 5 } Event = Struct.new(:type) do def initialize(**attrs) attrs.each { |k, v| self[k] = v } end def score SCORES.fetch(self.type) { 0 } end end end
Eyewritecode/igihe
igihe.rb
<gh_stars>1-10 require 'open-uri' require 'nokogiri' category = ARGV.first base_url = "http://igihe.com/" articles =[] article_num =0 trash = Nokogiri::HTML(open("http://igihe.com/#{category}")) puts "\nHi! i found these articles for you:" puts "\n############################################\n" trash.css(".homenews-title a").each do |h| puts article_num.to_s+" " +h.text article_num +=1 articles << h.attr("href").to_s end print "\nSelect one to check its comments> " article_number = STDIN.gets.chomp().to_i while(article_number > articles.length) || articles.empty? puts "Sorry we couldn't get that article" print "Select another article> " article_number = STDIN.gets.chomp().to_i end article = Nokogiri::HTML(open("#{base_url}#{articles[article_number]}")) article.css(".commentaires-section #iframe").each do |comments| #go to comments document iframe = Nokogiri::HTML(open("#{base_url}#{comments.attr('src')}")) iframe.css(".comments-text").each do |posts| puts posts.text end end
ManuelAF/click-to-deploy
vm/chef/cookbooks/erpnext/recipes/default.rb
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. apt_update do action :update end node['erpnext']['mariadb']['packages'].each do |pkg| apt_preference pkg do pin "version #{node['erpnext']['mariadb']['apt_version']}" pin_priority '1000' end end package 'Install packages' do package_name node['erpnext']['mariadb']['packages'] action :install end package 'Install packages' do package_name node['erpnext']['packages'] action :install end # Create frappe user. user node['erpnext']['frappe']['user'] do action :create home "/home/#{node['erpnext']['frappe']['user']}" shell '/bin/bash' password node['erpnext']['frappe']['password'] manage_home true end # Add frappe user to sudo. template "/etc/sudoers.d/#{node['erpnext']['frappe']['user']}" do source 'etc-sudoers.d-frappeuser.erb' owner 'root' group 'root' mode '0440' verify 'visudo -c -f %{path}' variables(frappeuser: node['erpnext']['frappe']['user']) end bash 'Set MariaDB root password' do code <<-EOH mysqladmin -uroot password "#{node['erpnext']['mysql-root-password']}" mysql -uroot -p"#{node['erpnext']['mysql-root-password']}" <<EOSQL DELETE FROM mysql.user WHERE User=''; DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '12192.168.127.12', '::1'); FLUSH PRIVILEGES; EOSQL EOH end # Add required MariaDB configuration cookbook_file '/etc/mysql/mariadb.conf.d/70-frappe.cnf' do source 'frappe.cnf' owner 'root' group 'root' mode 0664 action :create end service 'mysql' do action :restart end # Install NodeJS remote_file "/home/#{node['erpnext']['frappe']['user']}/setup_nodejs" do source "https://deb.nodesource.com/setup_#{node['erpnext']['nodejs']['version']}.x" action :create end bash 'Setup nodejs' do code <<-EOH bash /home/#{node['erpnext']['frappe']['user']}/setup_nodejs EOH end package 'Install nodejs' do package_name 'nodejs' action :install end bash 'Install yarn' do code <<-EOH npm install -g yarn EOH end bash 'Install bench' do code <<-EOH pip3 install frappe-bench EOH end bash 'Init bench' do code <<-EOH su - #{node['erpnext']['frappe']['user']} -c \ "bench init \ --frappe-branch version-#{node['erpnext']['version']} \ --python /usr/bin/python3 \ #{node['erpnext']['frappe']['bench']}" EOH end bash 'Create bench site' do user node['erpnext']['frappe']['user'] cwd "/home/#{node['erpnext']['frappe']['user']}/#{node['erpnext']['frappe']['bench']}" code <<-EOH bench new-site \ --mariadb-root-password="#{node['erpnext']['mysql-root-password']}" \ --admin-password="#{node['erpnext']['erpnext-admin-password']}" \ #{node['erpnext']['site']} EOH end bash 'Install erpnext app' do user node['erpnext']['frappe']['user'] cwd "/home/#{node['erpnext']['frappe']['user']}/#{node['erpnext']['frappe']['bench']}" code <<-EOH bench get-app --branch version-#{node['erpnext']['version']} erpnext bench --site #{node['erpnext']['site']} install-app erpnext bench --site #{node['erpnext']['site']} enable-scheduler EOH end bash 'Setup production' do user node['erpnext']['frappe']['user'] cwd "/home/#{node['erpnext']['frappe']['user']}/#{node['erpnext']['frappe']['bench']}" code <<-EOH sudo bench setup production #{node['erpnext']['frappe']['user']} --yes EOH end # Save initial root password. Will be changed during startup. file '/mysql_initial_password' do content node['erpnext']['mysql-root-password'] end # Cleanup sudoers file. file "/etc/sudoers.d/#{node['erpnext']['frappe']['user']}" do action :delete end # Cleanup nodejs setup script. file "/home/#{node['erpnext']['frappe']['user']}/setup_nodejs" do action :delete end c2d_startup_script 'erpnext-setup'
cpb/sexp_cli_tools
lib/sexp_cli_tools.rb
# frozen_string_literal: true require 'ruby_parser' require_relative 'sexp_cli_tools/version' require_relative 'sexp_cli_tools/matchers/super_caller' require_relative 'sexp_cli_tools/matchers/method_implementation' module SexpCliTools class Error < StandardError; end MATCHERS = Hash .new { |hash, key| hash[key] = Sexp::Matcher.parse(key) } .merge({ 'child-class' => Sexp::Matcher.parse('(class _ (const _) ___)'), 'parent-class' => Sexp::Matcher.parse('(class _ [not? (const _)] ___)'), 'super-caller' => Matchers::SuperCaller, 'method-implementation' => Matchers::MethodImplementation }) end
cpb/sexp_cli_tools
lib/sexp_cli_tools/matchers/method_implementation.rb
# frozen_string_literal: true module SexpCliTools module Matchers # A matcher that's satisfied by an s-expression containing a method definition. class MethodImplementation def self.satisfy?(sexp, target_method) new(target_method).satisfy?(sexp) end def initialize(target_method) @matcher = Sexp::Matcher.parse("[child (defn #{target_method} ___)]") end def satisfy?(sexp) @matcher.satisfy?(sexp) end end end end
cpb/sexp_cli_tools
test/fixtures/generic_empty_class.rb
<filename>test/fixtures/generic_empty_class.rb # frozen_string_literal: true class Bicycle # foo end
cpb/sexp_cli_tools
test/sexp_cli_tools/matchers/method_implementation_test.rb
# frozen_string_literal: true require 'test_helper' module SexpExamples def self.included(base) base.let(:sexp_with_initialize) { parse_file('road_bike.rb') } base.let(:sexp_without_initialize) do RubyParser.new.parse(<<~EMPTY_CLASS_DEFINITION) class Scooter end EMPTY_CLASS_DEFINITION end end end describe 'SexpCliTools::Matchers::MethodImplementation.satisfy?' do subject { SexpCliTools::Matchers::MethodImplementation } include SexpExamples it 'is satisfied by a ruby file which implements initialize' do _(subject.satisfy?(sexp_with_initialize, 'initialize')).must_equal true end it 'is not satisfied by a ruby file without an implementation of initialize' do _(subject.satisfy?(sexp_without_initialize, 'initialize')).must_equal false end end describe 'SexpCliTools::Matchers::MethodImplementation#satisfy?(sexp)' do subject { SexpCliTools::Matchers::MethodImplementation.new(target_method) } let(:target_method) { :initialize } include SexpExamples it 'is satisfied by a ruby file which implements initialize' do _(subject).must_be :satisfy?, sexp_with_initialize end it 'is not satisfied by a ruby file without an implementation of initialize' do _(subject).wont_be :satisfy?, sexp_without_initialize end end
cpb/sexp_cli_tools
test/test_helper.rb
<filename>test/test_helper.rb # frozen_string_literal: true $LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'sexp_cli_tools' require 'minitest/autorun' require 'pry' def fixture_path(basename, relative_path = Pathname.new('test/fixtures/coupling_between_superclasses_and_subclasses')) relative_path.join(basename) end def fixture_code(path) fixture_path(path).read end def parse_file(basename) RubyParser.new.parse(fixture_code(basename), fixture_path(basename)) end module CliTestHelpers module TestVariableSetup def prepare_workspace_hook before do setup_aruba prepend_environment_variable 'PATH', File.expand_path('../../exe:', __dir__) copy_fixtures_to_workspace end end def setup_command_result_inferred_subject let(:command_results) do run_command_and_stop command.gsub('%/', '') last_command_started.stdout end let(:command) { class_name.split('::', 3).last } subject { command_results } end end def self.included(base) require 'aruba' base.send(:include, Aruba::Api) base.send(:extend, TestVariableSetup) base.prepare_workspace_hook base.setup_command_result_inferred_subject end def copy_fixtures_to_workspace Pathname.glob('test/fixtures/**/*').each do |path| relative = path.relative_path_from('test/fixtures').to_s copy "%/#{relative}", relative end end end
cpb/sexp_cli_tools
test/sexp_cli_tools/matchers/super_caller_test.rb
<reponame>cpb/sexp_cli_tools # frozen_string_literal: true require 'test_helper' module SuperCallerExamples def self.included(base) base.let(:without_super_caller) { parse_file('bicycle.rb') } base.let(:with_super_caller) { parse_file('road_bike.rb') } base.let(:with_super_caller_no_args) { parse_file('mountain_bike.rb') } end end describe 'SexpCliTools::Matchers::SuperCaller' do subject { SexpCliTools::Matchers::SuperCaller } include SuperCallerExamples it 'is not satisfied by a ruby file without a method calling super' do _(subject).wont_be :satisfy?, without_super_caller end it 'is satisfied by a ruby file with a method calling super(args)' do _(subject).must_be :satisfy?, with_super_caller end it 'is satisfied by a ruby file with a call to super' do _(subject).must_be :satisfy?, with_super_caller_no_args end end describe 'SexpCliTools::Matchers::SuperCaller.satisfy? returned SexpMatchData#signature' do subject { SexpCliTools::Matchers::SuperCaller.satisfy?(sexp)&.map(&:signature) } include SuperCallerExamples describe 'with an sexp with a call to super' do let(:sexp) { with_super_caller_no_args } it 'lists matched method names' do _(subject).must_include 'MountainBike#initialize' _(subject).must_include 'MountainBike#spares' end end describe 'with an sexp with a call to super passing args' do let(:sexp) { with_super_caller } it 'lists matched method names' do _(subject).must_include 'RoadBike#initialize' _(subject).must_include 'RoadBike#spares' end end describe 'with an sexp without a call to super' do let(:sexp) { without_super_caller } it { assert_nil subject } end end describe 'SexpCliTools::Matchers::SuperCaller::SexpMatchData#to_mermaid' do subject { SexpCliTools::Matchers::SuperCaller::SexpMatchData.new('A#b', 'B#b').to_mermaid } it 'connects the signature to the super_signature' do _(subject).must_equal('A#b --> |super| B#b') end end describe 'SexpCliTools::Matchers::SuperCaller.satisfy? returned SexpMatchData#as_json' do # rubocop:disable Metrics/BlockLength subject { SexpCliTools::Matchers::SuperCaller.satisfy?(sexp)&.map(&:as_json) } include SuperCallerExamples describe 'with an sexp with a call to super' do let(:sexp) { with_super_caller_no_args } it 'lists inferred superclass method signatures' do expect(subject).must_include( { sender: { path: fixture_path('mountain_bike.rb'), signature: 'MountainBike#initialize' }, receiver: { signature: 'Bicycle#initialize' } } ) expect(subject).must_include( { sender: { path: fixture_path('mountain_bike.rb'), signature: 'MountainBike#spares' }, receiver: { signature: 'Bicycle#spares' } } ) end end describe 'with an sexp with a call to super passing args' do let(:sexp) { with_super_caller } it 'lists inferred superclass method signatures' do expect(subject).must_include( { sender: { path: fixture_path('road_bike.rb'), signature: 'RoadBike#initialize' }, receiver: { signature: 'Bicycle#initialize' } } ) expect(subject).must_include( { sender: { path: fixture_path('road_bike.rb'), signature: 'RoadBike#spares' }, receiver: { signature: 'Bicycle#spares' } } ) end end describe 'with an sexp without a call to super' do let(:sexp) { without_super_caller } it { assert_nil subject } end end describe 'SexpCliTools::Matchers::SuperCaller.satisfy? returned SexpMatchData#super_signature' do subject { SexpCliTools::Matchers::SuperCaller.satisfy?(sexp)&.map(&:super_signature) } include SuperCallerExamples describe 'with an sexp with a call to super' do let(:sexp) { with_super_caller_no_args } it 'lists inferred superclass method signatures' do expect(subject).must_include 'Bicycle#initialize' expect(subject).must_include 'Bicycle#spares' end end describe 'with an sexp with a call to super passing args' do let(:sexp) { with_super_caller } it 'lists inferred superclass method signatures' do expect(subject).must_include 'Bicycle#initialize' expect(subject).must_include 'Bicycle#spares' end end describe 'with an sexp without a call to super' do let(:sexp) { without_super_caller } it { assert_nil subject } end end describe 'SexpCliTools::Matchers::SuperCaller#in_superclass(String)' do let(:matcher) { SexpCliTools::Matchers::SuperCaller.new } it 'does not modify the String parameter for #superclass_name in the block' do matcher.in_superclass 'SuperclassName' do _(matcher.superclass_name).must_equal 'SuperclassName' end end it 'does not stack superclasses into namespaces' do matcher.in_superclass 'SuperclassName' do matcher.in_superclass 'FunkyStructure' do _(matcher.superclass_name).must_equal 'FunkyStructure' end _(matcher.superclass_name).must_equal 'SuperclassName' end end end describe 'SexpCliTools::Matchers::SuperCaller#in_superclass(Sexp)' do let(:matcher) { SexpCliTools::Matchers::SuperCaller.new } def s(*args) Sexp.new(*args) end it 'turns namespaced constant s-expressions into class names' do matcher.in_superclass s(:colon2, s(:const, :X), :Y) do _(matcher.superclass_name).must_equal 'X::Y' end end it 'turns namespace busting s-expressions into class names' do matcher.in_superclass s(:colon3, :Y) do _(matcher.superclass_name).must_equal 'Y' end end end
cpb/sexp_cli_tools
lib/sexp_cli_tools/cli.rb
# frozen_string_literal: true require 'thor' require 'sexp_cli_tools' module SexpCliTools # Top-level command-line interface defining public shell interface. class Cli < Thor desc 'version', 'Prints version' default_command def version puts format('SexpCliTools version: %p', SexpCliTools::VERSION) end option :json, default: false, type: :boolean option :include, default: ['**/*.rb'], type: :array desc 'find sexp-matcher [--include **/*.rb]', 'Finds Ruby files matching the s-expression matcher in the `include` glob pattern or file list.' def find(requested_sexp_matcher, *matcher_params) paths = Glob.new(options[:include]) sexp_matcher = SexpCliTools::MATCHERS[requested_sexp_matcher] paths .reduce(build_buffer(**kwargs(options))) do |output, path| matches = sexp_matcher.satisfy?(sexp(path), *matcher_params) output << emit(path, matches, **kwargs(options)) end .flush end # Enumerable reducer of globs to paths class Glob include Enumerable def initialize(globs) @globs = Array(globs) end def each(&block) @globs.each do |glob| Pathname.glob(glob).each(&block) end end end # Provides a stream like interface to emitting json class JSONBuffer def initialize @received = [] end def <<(elements) @received.push(*elements) self end def flush puts JSON.pretty_generate(@received) end end # Provides a stream like interface to emitting filenames class PathBuffer def initialize @received = [] end def <<(elements) @received.push(*elements) self end def flush puts @received end end no_commands do def build_buffer(json:, **_) if json JSONBuffer.new else PathBuffer.new end end def sexp(path) RubyParser.new.parse(path.read, path) end def kwargs(indifferent_hash) indifferent_hash.transform_keys(&:to_sym) end def emit(path, matches, json:, **_) return unless matches if json matches else path end end end end end
cpb/sexp_cli_tools
test/fixtures/coupling_between_superclasses_and_subclasses/mountain_bike.rb
<filename>test/fixtures/coupling_between_superclasses_and_subclasses/mountain_bike.rb # frozen_string_literal: true class MountainBike < Bicycle attr_reader :front_shock, :rear_shock def initialize(args) @front_shock = args[:front_shock] @rear_shock = args[:rear_shock] super(args) end def spares super.merge({ rear_shock: rear_shock }) end def default_tire_size '2.1' end end
cpb/sexp_cli_tools
lib/sexp_cli_tools/version.rb
<gh_stars>1-10 # frozen_string_literal: true module SexpCliTools VERSION = '1.0.0' end
cpb/sexp_cli_tools
test/fixtures/no_initialize.rb
# frozen_string_literal: true # Test fixture for `sexp find method-implementation initialize` class NoInitialize def some_other_method; end end
cpb/sexp_cli_tools
test/fixtures/coupling_between_superclasses_and_subclasses/bicycle.rb
# frozen_string_literal: true class Bicycle attr_reader :size, :chain, :tire_size def initialize(args) @size = args[:size] @chain = args[:chain] || default_chain @tire_size = args[:tire_size] || default_tire_size end def default_chain '10-speed' end def default_tire_size raise NotImplementedError end end
cpb/sexp_cli_tools
test/fixtures/coupling_between_superclasses_and_subclasses/road_bike.rb
<reponame>cpb/sexp_cli_tools<filename>test/fixtures/coupling_between_superclasses_and_subclasses/road_bike.rb # frozen_string_literal: true class RoadBike < Bicycle attr_reader :tape_color def initialize(args) @tape_color = args[:tape_color] super(args) end def spares super.merge({ tape_color: tape_color }) end def default_tire_size '21' end end
cpb/sexp_cli_tools
lib/sexp_cli_tools/matchers/super_caller.rb
<reponame>cpb/sexp_cli_tools<filename>lib/sexp_cli_tools/matchers/super_caller.rb # frozen_string_literal: true require 'sexp_processor' require 'json' module SexpCliTools module Matchers # Matches a call to `super` and captures the method name of calling `super` class SuperCaller < MethodBasedSexpProcessor # Thanks to this test: https://github.com/seattlerb/sexp_processor/blob/93712e31b6d5e23c7d68cea805b40a642aad3e10/test/test_sexp.rb#L1625 # zsuper I noticed while simplifying the examples MATCHER = Sexp::Matcher.parse('[child (super ___)]') | Sexp::Matcher.parse('[child (zsuper)]') SexpMatchData = Struct.new(:signature, :super_signature, :path) do def to_mermaid [signature, super_signature].join(' --> |super| ') end def to_json(*args) as_json.to_json(*args) end def as_json { sender: { path: path, signature: signature }, receiver: { signature: super_signature } } end end def self.satisfy?(sexp) processor = new processor.process(sexp) processor.matches if processor.matched? end attr_reader :matches def initialize(*) super @matches = [] @superclasses = [] end def in_superclass(superclass_expression, &block) @superclasses << sexp_to_classname(superclass_expression) block.call if block_given? @superclasses.pop end def superclass_name @superclasses.last end def super_signature [superclass_name, method_name].join end def process_defn(exp) super do @matches << SexpMatchData.new(signature, super_signature, exp.file) if exp.satisfy?(MATCHER) end end # Probably good for detection, but observes without the context we # need to relocate. # def process_super(exp) # @matches << SexpMatchData.new(signature, super_signature) # exp # end # # def process_zsuper(exp) # @matches << SexpMatchData.new(signature, super_signature) # exp # end def process_class(exp) super do possible_superclass = exp.shift if possible_superclass in_superclass(possible_superclass) do process_until_empty exp end end end end def matched? !@matches.empty? end private def sexp_to_classname(sexp) return sexp unless sexp.is_a?(Sexp) type, *rest = sexp case type when :colon3, :const rest.first.to_s when :colon2 [rest.first.last, rest.last].join('::') else raise NotImplemented, "haven't handled #{type} yet" end end end end end
cpb/sexp_cli_tools
test/sexp_cli_tools/cli_test.rb
<filename>test/sexp_cli_tools/cli_test.rb # frozen_string_literal: true require 'test_helper' describe 'sexp' do include CliTestHelpers it { _(subject).must_match(/SexpCliTools version: "\d+\.\d+\.\d+"/) } end describe 'sexp find child-class' do include CliTestHelpers it "doesn't match our parent class" do _(subject).wont_match(/bicycle.rb/) end it 'does match our child class' do _(subject).must_match(/mountain_bike.rb/) _(subject).must_match(/road_bike.rb/) end end describe 'sexp find child-class --include coupling_between_superclasses_and_subclasses/mountain_bike.rb' do include CliTestHelpers it "doesn't list classes not in the --include" do _(subject).wont_match(/road_bike.rb/) end it 'does list matching files in the --include' do _(subject).must_match(/mountain_bike.rb/) end end included_files = %w[ coupling_between_superclasses_and_subclasses/road_bike.rb coupling_between_superclasses_and_subclasses/mountain_bike.rb ] describe "sexp find child-class --include #{included_files.join(' ')}" do include CliTestHelpers it 'does lists matches among all files in the --include' do _(subject).must_match(/mountain_bike.rb/) _(subject).must_match(/road_bike.rb/) end end describe 'sexp find parent-class' do include CliTestHelpers it "doesn't match our child classes" do _(subject).wont_match(/mountain_bike.rb/) _(subject).wont_match(/road_bike.rb/) end it 'does match our parent class' do _(subject).must_match(/bicycle.rb/) end end describe 'sexp find super-caller' do include CliTestHelpers it "doesn't match our parent class" do _(subject).wont_match(/bicycle.rb/) end it 'does match our child class' do _(subject).must_match(/mountain_bike.rb/) _(subject).must_match(/road_bike.rb/) end end describe 'sexp find super-caller --json' do # rubocop:disable Metrics/BlockLength include CliTestHelpers it 'lists match data inferences' do _(subject).must_match(<<~EXPECTED_JSON) [ { "sender": { "path": "coupling_between_superclasses_and_subclasses/mountain_bike.rb", "signature": "MountainBike#initialize" }, "receiver": { "signature": "Bicycle#initialize" } }, { "sender": { "path": "coupling_between_superclasses_and_subclasses/mountain_bike.rb", "signature": "MountainBike#spares" }, "receiver": { "signature": "Bicycle#spares" } }, { "sender": { "path": "coupling_between_superclasses_and_subclasses/road_bike.rb", "signature": "RoadBike#initialize" }, "receiver": { "signature": "Bicycle#initialize" } }, { "sender": { "path": "coupling_between_superclasses_and_subclasses/road_bike.rb", "signature": "RoadBike#spares" }, "receiver": { "signature": "Bicycle#spares" } } ] EXPECTED_JSON end end describe "sexp find '(class ___)'" do include CliTestHelpers it 'lists all files with classes defined' do _(subject).must_match(/bicycle.rb/) _(subject).must_match(/mountain_bike.rb/) _(subject).must_match(/road_bike.rb/) end end describe 'sexp find method-implementation initialize' do include CliTestHelpers it 'lists the bicycle.rb and road_bike.rb files, which implements the initialize' do _(subject).must_match(/bicycle.rb/) _(subject).must_match(/road_bike.rb/) end it "doest not list no_initialize, doesn't have initialize" do _(subject).wont_match(/no_initialize.rb/) end end
cpb/sexp_cli_tools
test/sexp_cli_tools_test.rb
# frozen_string_literal: true require 'test_helper' describe SexpCliTools do it 'has a version number' do refute_nil SexpCliTools::VERSION end describe "MATCHERS['(class ___)']" do subject { SexpCliTools::MATCHERS['(class ___)'] } let(:a_class_sexp) { RubyParser.new.parse('class Foobar; end') } it 'matches a class' do _(subject).must_be :satisfy?, a_class_sexp end end end
mathieujobin/weak_parameters
lib/weak_parameters.rb
require "active_support/hash_with_indifferent_access" require "active_support" require 'active_support/core_ext/object/blank' require "weak_parameters/base_validator" require "weak_parameters/any_validator" require "weak_parameters/array_validator" require "weak_parameters/boolean_validator" require "weak_parameters/file_validator" require "weak_parameters/date_validator" require "weak_parameters/time_validator" require "weak_parameters/float_validator" require "weak_parameters/hash_validator" require "weak_parameters/integer_validator" require "weak_parameters/string_validator" require "weak_parameters/object_validator" require "weak_parameters/list_validator" require "weak_parameters/controller" require "weak_parameters/validation_error" require "weak_parameters/validator" require "weak_parameters/version" module WeakParameters def self.stats @stats ||= ActiveSupport::HashWithIndifferentAccess.new do |hash, key| hash[key] = ActiveSupport::HashWithIndifferentAccess.new end end class Railties < ::Rails::Railtie initializer 'weak_parameters' do ActiveSupport.on_load :action_controller do ActionController::Base.extend WeakParameters::Controller ActionController::API.extend WeakParameters::Controller if Object.const_defined?('ActionController::API') end end end end
mathieujobin/weak_parameters
spec/requests/strong_spec.rb
require "spec_helper" describe "Strong", type: :request do let(:params) do { object: [1], strong_object: [1], name: "name", strong_name: "name", number: 0, strong_number: 0, type: 1, strong_type: 1, flag: true, strong_flag: true, config: { a: 1 }, strong_config: { a: 1, b: { c: 2 } }, tags: [1], strong_tags: [1], rate: 0.01, strong_rate: 0.01, date: Date.current.strftime('%Y-%m-%d'), strong_date: Date.current.strftime('%Y-%m-%d'), time: Time.current.strftime('%Y-%m-%d %H:%M:%S'), strong_time: Time.current.strftime('%Y-%m-%d %H:%M:%S'), attachment: Rack::Test::UploadedFile.new(__FILE__), strong_attachment: Rack::Test::UploadedFile.new(__FILE__), zip_code: "123-4567", strong_zip_code: "123-4567", custom: 0, strong_custom: 0, nested: { number: 0 }, strong_nested: { strong_number: 0 }, numbers: [1, 2, 3], strong_numbers: [1, 2, 3], body: { items: [ { name: "foo", price: 100 }, { name: "bar", price: 100 } ] }, strong_body: { items: [ { name: "foo", strong_price: 100 }, { name: "bar", strong_price: 100 } ] } } end describe "#permitted_params" do it "returns permitted_params" do post "/strongs", params: params expect(controller.permitted_params).to have_key "strong_object" expect(controller.permitted_params).not_to have_key "object" expect(controller.permitted_params).to have_key "strong_name" expect(controller.permitted_params).not_to have_key "name" expect(controller.permitted_params).to have_key "strong_number" expect(controller.permitted_params).not_to have_key "number" expect(controller.permitted_params).to have_key "strong_type" expect(controller.permitted_params).not_to have_key "type" expect(controller.permitted_params).to have_key "strong_flag" expect(controller.permitted_params).not_to have_key "flag" expect(controller.permitted_params).to have_key "strong_config" expect(controller.permitted_params).not_to have_key "config" expect(controller.permitted_params).to have_key "strong_tags" expect(controller.permitted_params).not_to have_key "tags" expect(controller.permitted_params).to have_key "strong_rate" expect(controller.permitted_params).not_to have_key "rate" expect(controller.permitted_params).to have_key "strong_date" expect(controller.permitted_params).not_to have_key "date" expect(controller.permitted_params).to have_key "strong_time" expect(controller.permitted_params).not_to have_key "time" expect(controller.permitted_params).to have_key "strong_attachment" expect(controller.permitted_params).not_to have_key "attachment" expect(controller.permitted_params).to have_key "strong_zip_code" expect(controller.permitted_params).not_to have_key "zip_code" expect(controller.permitted_params).to have_key "strong_custom" expect(controller.permitted_params).not_to have_key "custom" expect(controller.permitted_params).to have_key "strong_nested" expect(controller.permitted_params).not_to have_key "nested" expect(controller.permitted_params).to have_key "strong_numbers" expect(controller.permitted_params).not_to have_key "numbers" expect(controller.permitted_params).to have_key "strong_body" expect(controller.permitted_params).not_to have_key "body" expect(controller.permitted_params[:strong_body]).to have_key "items" expect(controller.permitted_params[:strong_body][:items].first).to have_key "strong_price" expect(controller.permitted_params[:strong_body][:items].first).not_to have_key "name" end end end
uuttff8/DeclarativeLayoutKit
DeclarativeLayoutKit.podspec
Pod::Spec.new do |spec| spec.name = "DeclarativeLayoutKit" spec.version = "3.0.3" spec.summary = "UIKit declarative layout like SwiftUI." spec.homepage = "https://github.com/Ernest0-Production/DeclarativeLayoutKit" spec.license = { :type => "MIT", :file => "LICENSE.md" } spec.author = { "Ernest" => "<EMAIL>" } spec.platform = :ios spec.ios.deployment_target = '11.0' spec.swift_versions = '5.4' spec.source_files = "Sources/DeclarativeLayoutKit/**/*.swift" spec.source = { :git => "https://github.com/Ernest0-Production/DeclarativeLayoutKit.git", :branch => "master", :tag => "#{spec.version}" } end
ruddfawcett/hoot
lib/hoot/client.rb
require 'json' require 'net/https' require 'uri' module Hoot unless ENV['DEV'] HEDWING_ENDPOINT = 'https://hedwig.herokuapp.com' else HEDWING_ENDPOINT = 'http://localhost:5000' end class Client attr_accessor :hedwig attr_accessor :credentials def initialize @hedwig = ENV['HEDWING_ENDPOINT'] || HEDWING_ENDPOINT end def push(message = nil) @credentials = Hoot::Keychain::credentials if message.nil? message = 'Hoot! Your command has completed! Come back!' end data = { :credentials => { :email => @credentials[0], :password => <PASSWORD>] }, :message => message, :metadata => Hoot::Metadata.get } response = request('send', data) if response['result'] abort('A Hoot was sent to your device.') end abort('A server error occurred.') end def authenticate(credentials) data = { :credentials => { :email => credentials[0], :password => <PASSWORD>] } } response = request('authenticate', data) if response['result'] Hoot::Keychain.save(credentials) abort('Authentication successful.') end puts 'Authentication failed.' Hoot::User::login end private def request(path, data) uri = URI.parse(@hedwig) http = Net::HTTP.new(uri.host, uri.port) unless ENV['DEV'] http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER end data = encode(data) request = Net::HTTP::Post.new("/api/v1/#{path}") request.add_field('Content-Type', 'application/json') request.set_form_data(data) response = http.request(request) JSON.parse(response.body) end # http://dev.mensfeld.pl/2012/01/converting-nested-hash-into-http-url-params-hash-version-in-ruby/ def encode(value, key = nil, out_hash = {}) case value when Hash then value.each { |k,v| encode(v, append_key(key,k), out_hash) } out_hash when Array then value.each { |v| encode(v, "#{key}[]", out_hash) } out_hash when nil then '' else out_hash[key] = value out_hash end end def append_key(root_key, key) root_key.nil? ? :"#{key}" : :"#{root_key}[#{key.to_s}]" end end end
ruddfawcett/hoot
lib/hoot/metadata.rb
<reponame>ruddfawcett/hoot require 'yaml' module Hoot module Metadata @path = "#{ENV['HOME']}/.hoot/metadata.yml" public def self.set(key, value) return if value.nil? return unless keys.include?(key) create unless File.exist?(@path) if File.exist?(@path) @m = YAML::load_file(@path) end if @m.nil? || @m == false @m = {} end if valid?(key, value) # key = key.to_s Still not sure if I want to remove the ':' from the .yml file. @m[key] = value save else abort('You are trying to set invalid options.') end end def self.get return YAML::load_file(@path) if File.exist?(@path) end def self.save if File.write(@path, @m.to_yaml) true else false end end protected def self.create path = "#{ENV['HOME']}/.hoot/" Dir.mkdir(path) unless File.exists?(path) File.new(@path, 'w') end def self.valid?(key, value) return false unless keys.include?(key) return true unless key == :device= return false unless values.include?(value.to_sym) end def self.keys [ :description, :device ] end def self.values [ :server, :laptop, :desktop ] end end end
ruddfawcett/hoot
hoot.gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'hoot/version' Gem::Specification.new do |s| s.name = "hoot" s.version = Hoot::VERSION s.authors = ["<NAME>"] s.email = ["<EMAIL>"] s.summary = "Send push notifications to your phone when a Terminal process has completed." s.description = "" s.homepage = "https://github.com/ruddfawcett/hoot" s.license = "MIT" s.add_dependency "netrc" s.add_dependency "commander" s.add_dependency "json" s.files = Dir["./**/*"].reject { |file| file =~ /\.\/(bin|log|pkg|script|spec|test|vendor)/ } s.executables = ["hoot"] s.require_paths = ["lib"] s.add_development_dependency "bundler", "~> 1.10" s.add_development_dependency "rake", "~> 10.0" end
ruddfawcett/hoot
lib/hoot.rb
<gh_stars>1-10 require 'hoot/client' require 'hoot/keychain' require 'hoot/metadata' require 'hoot/user' require 'hoot/version'
ruddfawcett/hoot
lib/hoot/user.rb
<gh_stars>1-10 require 'commander/import' module Hoot module User @client = Hoot::Client.new def self.login puts 'Enter your Hoot credentials.' email = ask 'Email: ' password = Digest::SHA1.hexdigest(password 'Password: ', '*') credentials = [email, password] @client.authenticate(credentials) end def self.logout Hoot::Keychain.destroy end end end
ruddfawcett/hoot
lib/hoot/keychain.rb
<gh_stars>1-10 require 'netrc' require 'digest/sha1' module Hoot module Keychain @n = Netrc.read public def self.authenticated? login, password = @n['hedwig.herokuapp.com'] if (login.nil? || login == 0) || (password.nil? || password == 0) return false end return true end def self.credentials if authenticated? return @n['hedwig.herokuapp.com'] end nil end def self.save(credentials) @n['hedwig.herokuapp.com'] = credentials[0], credentials[1] @n.save end def self.destroy @n['hedwig.herokuapp.com'] = 0, 0 @n.save abort('You were logged out.') end end end
fossabot/binance-api-ruby
spec/spec_helper.rb
require "bundler/setup" require "binance_api" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. Dir["#{__dir__}/support/**/*.rb"].each { |f| require f }
fossabot/binance-api-ruby
lib/binance_api/base.rb
<filename>lib/binance_api/base.rb require 'rest-client' require 'date' require 'uri' require 'json' require 'binance_api/result' module BinanceAPI class Base BASE_URL = 'https://api.binance.com'.freeze protected def params_with_signature(params, secret) params = params.reject { |_k, v| v.nil? } query_string = URI.encode_www_form(params) signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, query_string) params = params.merge(signature: signature) end # ensure to return a response object def safe yield rescue RestClient::ExceptionWithResponse => err return err.response end def config @config ||= BinanceAPI.load_config end def api_key config['API_KEY'].freeze end def api_secret config['API_SECRET'].freeze end end end
fossabot/binance-api-ruby
lib/binance_api/rest.rb
require 'rest-client' require 'date' require 'uri' require 'json' require 'binance_api/base' require 'binance_api/result' module BinanceAPI class REST < BinanceAPI::Base def ping response = safe { RestClient.get("#{BASE_URL}/api/v1/ping") } build_result response end def server_time response = safe { RestClient.get("#{BASE_URL}/api/v1/time") } build_result response end def exchange_info response = safe { RestClient.get("#{BASE_URL}/api/v1/exchangeInfo") } build_result response end def depth(symbol, limit: 100) response = safe { RestClient.get("#{BASE_URL}/api/v1/depth", params: { symbol: symbol, limit: limit }) } build_result response end def trades(symbol, limit: 500) response = safe { RestClient.get("#{BASE_URL}/api/v1/trades", params: { symbol: symbol, limit: limit }) } build_result response end def historical_trades(symbol, limit: 500, from_id: nil) params = { symbol: symbol, limit: limit } params = params.merge(fromId: from_id) unless from_id.nil? response = safe do RestClient.get "#{BASE_URL}/api/v1/historicalTrades", params: params, 'X-MBX-APIKEY' => api_key end build_result response end def aggregate_trades_list(symbol, from_id: nil, start_time: nil, end_time: nil, limit: 500) params = begin { symbol: symbol, limit: limit }.tap do |_params| _params[:fromId] = from_id unless from_id.nil? _params[:startTime] = start_time unless start_time.nil? _params[:endTime] = end_time unless end_time.nil? end end response = safe { RestClient.get("#{BASE_URL}/api/v1/aggTrades", params: params) } build_result response end def klines(symbol, interval, start_time: nil, end_time: nil, limit: 500) params = begin { symbol: symbol, interval: interval, limit: limit }.tap do |_params| _params[:startTime] = start_time unless start_time.nil? _params[:endTime] = end_time unless end_time.nil? end end response = safe { RestClient.get("#{BASE_URL}/api/v1/klines", params: params) } build_result response end def ticker_24hr(symbol) response = safe { RestClient.get("#{BASE_URL}/api/v1/ticker/24hr", params: { symbol: symbol }) } build_result response end def ticker_price(symbol) response = safe { RestClient.get("#{BASE_URL}/api/v3/ticker/price", params: { symbol: symbol }) } build_result response end def ticker_book(symbol) response = safe { RestClient.get("#{BASE_URL}/api/v3/ticker/bookTicker", params: { symbol: symbol }) } build_result response end # { # symbol: 'LTCBTC', # side: 'BUY', # type: 'LIMIT', # timeInForce: 'GTC', # quantity: 1, # price: 0.1, # recvWindow: BinanceAPI.recv_window, # timestamp: 1499827319559 # } def order(symbol, side, type, quantity, options = {}) recv_window = options.delete(:recv_window) || BinanceAPI.recv_window timestamp = options.delete(:timestamp) || Time.now params = { symbol: symbol, side: side, type: type, timeInForce: options.fetch(:time_in_force, nil), quantity: quantity, price: options.fetch(:price, nil), newClientOrderId: options.fetch(:new_client_order_id, nil), stopPrice: options.fetch(:stop_price, nil), icebergQty: options.fetch(:iceberg_qty, nil), newOrderRespType: options.fetch(:new_order_resp_type, nil), recvWindow: recv_window, timestamp: timestamp.to_i * 1000 # to milliseconds } response = safe do RestClient.post "#{BASE_URL}/api/v3/order", params_with_signature(params, api_secret), 'X-MBX-APIKEY' => api_key end build_result response end def order_test(symbol, side, type, quantity, options = {}) recv_window = options.delete(:recv_window) || BinanceAPI.recv_window timestamp = options.delete(:timestamp) || Time.now params = { symbol: symbol, side: side, type: type, timeInForce: options.fetch(:time_in_force, nil), quantity: quantity, price: options.fetch(:price, nil), newClientOrderId: options.fetch(:new_client_order_id, nil), stopPrice: options.fetch(:stop_price, nil), icebergQty: options.fetch(:iceberg_qty, nil), newOrderRespType: options.fetch(:new_order_resp_type, nil), recvWindow: recv_window, timestamp: timestamp.to_i * 1000 # to milliseconds } response = safe do RestClient.post "#{BASE_URL}/api/v3/order/test", params_with_signature(params, api_secret), 'X-MBX-APIKEY' => api_key end build_result response end def get_order(symbol, options = {}) recv_window = options.delete(:recv_window) || BinanceAPI.recv_window timestamp = options.delete(:timestamp) || Time.now params = { symbol: symbol, orderId: options.fetch(:order_id, nil), origClientOrderId: options.fetch(:orig_client_order_id, nil), recvWindow: recv_window, timestamp: timestamp.to_i * 1000 # to milliseconds } response = safe do RestClient.get "#{BASE_URL}/api/v3/order", params: params_with_signature(params, api_secret), 'X-MBX-APIKEY' => api_key end build_result response end def cancel_order(symbol, options = {}) recv_window = options.delete(:recv_window) || BinanceAPI.recv_window timestamp = options.delete(:timestamp) || Time.now params = { symbol: symbol, orderId: options.fetch(:order_id, nil), origClientOrderId: options.fetch(:orig_client_order_id, nil), newClientOrderId: options.fetch(:new_client_order_id, nil), recvWindow: recv_window, timestamp: timestamp.to_i * 1000 # to milliseconds } response = safe do RestClient.delete "#{BASE_URL}/api/v3/order", params: params_with_signature(params, api_secret), 'X-MBX-APIKEY' => api_key end build_result response end def open_orders(symbol, options = {}) recv_window = options.delete(:recv_window) || BinanceAPI.recv_window timestamp = options.delete(:timestamp) || Time.now params = { symbol: symbol, recvWindow: recv_window, timestamp: timestamp.to_i * 1000 # to milliseconds } response = safe do RestClient.get "#{BASE_URL}/api/v3/openOrders", params: params_with_signature(params, api_secret), 'X-MBX-APIKEY' => api_key end build_result response end def all_orders(symbol, options = {}) recv_window = options.delete(:recv_window) || BinanceAPI.recv_window timestamp = options.delete(:timestamp) || Time.now limit = options.delete(:limit) || 500 params = { symbol: symbol, orderId: options.fetch(:order_id, nil), limit: limit, recvWindow: recv_window, timestamp: timestamp.to_i * 1000 # to milliseconds } response = safe do RestClient.get "#{BASE_URL}/api/v3/allOrders", params: params_with_signature(params, api_secret), 'X-MBX-APIKEY' => api_key end build_result response end def account(options = {}) recv_window = options.delete(:recv_window) || BinanceAPI.recv_window timestamp = options.delete(:timestamp) || Time.now params = { recvWindow: recv_window, timestamp: timestamp.to_i * 1000 # to milliseconds } response = safe do RestClient.get "#{BASE_URL}/api/v3/account", params: params_with_signature(params, api_secret), 'X-MBX-APIKEY' => api_key end build_result response end def my_trades(symbol, options = {}) recv_window = options.delete(:recv_window) || BinanceAPI.recv_window timestamp = options.delete(:timestamp) || Time.now limit = options.delete(:limit) || 500 params = { symbol: symbol, limit: limit, fromId: options.fetch(:from_id, nil), recvWindow: recv_window, timestamp: timestamp.to_i * 1000 # to milliseconds } response = safe do RestClient.get "#{BASE_URL}/api/v3/myTrades", params: params_with_signature(params, api_secret), 'X-MBX-APIKEY' => api_key end build_result response end def start_user_data_stream response = safe do RestClient.post "#{BASE_URL}/api/v1/userDataStream", {}, 'X-MBX-APIKEY' => api_key end build_result response end def keep_alive_user_data_stream(listen_key) response = safe do RestClient.put "#{BASE_URL}/api/v1/userDataStream", {listenKey: listen_key}, 'X-MBX-APIKEY' => api_key end build_result response end def close_user_data_stream(listen_key) response = safe do RestClient.delete "#{BASE_URL}/api/v1/userDataStream", params: {listenKey: listen_key}, 'X-MBX-APIKEY' => api_key build_result response end end protected def build_result(response) json = JSON.parse(response.body, symbolize_names: true) BinanceAPI::Result.new(json, response.code == 200) end end end
fossabot/binance-api-ruby
lib/binance_api.rb
<reponame>fossabot/binance-api-ruby require 'binance_api/version' require 'binance_api/rest' require 'binance_api/wapi' require 'binance_api/stream' require 'yaml' module BinanceAPI class << self def rest @rest ||= BinanceAPI::REST.new end def wapi @wapi ||= BinanceAPI::WAPI.new end attr_writer :recv_window def recv_window @recv_window || 5000 end def load_config YAML.load_file(File.join(BinanceAPI.root, 'config', 'config.yml')) end def root File.expand_path('../..', __FILE__) end end end
Nerian/effective_resources
app/models/effective/resource_exec.rb
# Makes sure resource in any instance_execs is the correct resource module Effective class ResourceExec def initialize(instance, resource) @instance = instance @resource = resource end def resource @resource end def method_missing(method, *args, &block) @instance.send(method, *args) end end end
Nerian/effective_resources
app/models/effective/model_reader.rb
<reponame>Nerian/effective_resources module Effective class ModelReader DATATYPES = [:binary, :boolean, :date, :datetime, :decimal, :float, :hstore, :inet, :integer, :string, :text, :permitted_param] attr_reader :attributes def initialize(&block) @attributes = {} end def read(&block) instance_exec(&block) end def method_missing(m, *args, &block) if m == :timestamps attributes[:created_at] = [:datetime] attributes[:updated_at] = [:datetime] return end # Not really an attribute, just a permitted param. # something permitted: true if args.first.kind_of?(Hash) && args.first.key?(:permitted) args.unshift(:permitted_param) end # Specifying permitted param attributes # invitation [:name, :email], permitted: true if args.first.kind_of?(Array) options = args.find { |arg| arg.kind_of?(Hash) } || { permitted: true } args = [:permitted_param, options.merge(permitted_attributes: args.first)] end unless DATATYPES.include?(args.first) raise "expected first argument to be a datatype. Try name :string" end attributes[m] = args end end end
Nerian/effective_resources
app/controllers/concerns/effective/crud_controller/respond.rb
<reponame>Nerian/effective_resources<filename>app/controllers/concerns/effective/crud_controller/respond.rb module Effective module CrudController module Respond def respond_with_success(format, resource, action) if specific_redirect_path?(action) format.html do flash[:success] ||= resource_flash(:success, resource, action) redirect_to(resource_redirect_path(action)) end format.js do flash[:success] ||= resource_flash(:success, resource, action) redirect_to(resource_redirect_path(action)) end elsif template_present?(action) format.html do flash.now[:success] ||= resource_flash(:success, resource, action) render(action) # action.html.haml end format.js do flash.now[:success] ||= resource_flash(:success, resource, action) #reload_resource unless action == :destroy # Removed. render(action) # action.js.erb end else # Default format.html do flash[:success] ||= resource_flash(:success, resource, action) redirect_to(resource_redirect_path(action)) end format.js do flash.now[:success] ||= resource_flash(:success, resource, action) render(:member_action, locals: { action: action }) end end end def respond_with_error(format, resource, action) flash.delete(:success) flash.now[:danger] ||= resource_flash(:danger, resource, action) redirect_flash if specific_redirect_path?(:error) run_callbacks(:resource_render) if specific_redirect_path?(:error) format.html { redirect_to resource_redirect_path(:error) } format.js { redirect_to resource_redirect_path(:error) } return end # HTML responder case action.to_sym when :create format.html { render :new } when :update format.html { render :edit } when :destroy format.html do redirect_flash redirect_to(resource_redirect_path(action)) end else # member action format.html do if resource_edit_path && referer_redirect_path.to_s.end_with?(resource_edit_path) @page_title ||= "Edit #{resource}" render :edit elsif resource_new_path && referer_redirect_path.to_s.end_with?(resource_new_path) @page_title ||= "New #{resource_name.titleize}" render :new elsif resource_action_path(action) && referer_redirect_path.to_s.end_with?(resource_action_path(action)) && template_present?(action) @page_title ||= "#{action.to_s.titleize} #{resource}" render(action, locals: { action: action }) elsif resource_show_path && referer_redirect_path.to_s.end_with?(resource_show_path) @page_title ||= resource_name.titleize render :show else @page_title ||= resource.to_s redirect_flash redirect_to(referer_redirect_path || resource_redirect_path(action)) end end end format.js do view = template_present?(action) ? action : :member_action render(view, locals: { action: action }) # action.js.erb end end private def redirect_flash return unless flash.now[:danger].present? danger = flash.now[:danger] flash.now[:danger] = nil flash[:danger] ||= danger end def template_present?(action) lookup_context.template_exists?("#{action}.#{request.format.symbol.to_s.sub('json', 'js').presence || 'html'}", _prefixes) end end end end
Nerian/effective_resources
app/models/effective/resources/paths.rb
module Effective module Resources module Paths def model_file File.join('app/models', class_path.to_s, "#{name}.rb") end def controller_file File.join('app/controllers', namespace.to_s, "#{plural_name}_controller.rb") end def datatable_file File.join('app/datatables', namespace.to_s, "#{plural_name}_datatable.rb") end def view_file(action = :index, partial: false) File.join('app/views', namespace.to_s, (namespace.present? ? '' : class_path), plural_name, "#{'_' if partial}#{action}.html.haml") end def flat_view_file(action = :index, partial: false) File.join('app/views', plural_name, "#{'_' if partial}#{action}.html.haml") end end end end
Nerian/effective_resources
app/controllers/concerns/effective/crud_controller/permitted_params.rb
module Effective module CrudController module PermittedParams BLACKLIST = [:created_at, :updated_at, :logged_change_ids] # This is only available to models that use the effective_resource do ... end attributes block # It will be called last, and only for those resources # params.require(effective_resource.name).permit! def resource_permitted_params raise 'expected resource class to have effective_resource do .. end' if effective_resource.model.blank? permitted_params = permitted_params_for(resource, effective_resource.namespaces) if Rails.env.development? Rails.logger.info "Effective::CrudController#resource_permitted_params:" Rails.logger.info "params.require(:#{effective_resource.name}).permit(#{permitted_params.to_s[1...-1]})" end params.require(effective_resource.name).permit(*permitted_params) end # If the resource is ActiveModel, just permit all # This can still be overridden by a controller def resource_active_model_permitted_params if Rails.env.development? Rails.logger.info "Effective::CrudController#resource_permitted_params:" Rails.logger.info "params.require(:#{effective_resource.name}).permit!" end params.require(effective_resource.name).permit! end private def permitted_params_for(resource, namespaces = []) effective_resource = if resource.kind_of?(Class) resource.effective_resource if resource.respond_to?(:effective_resource) else resource.class.effective_resource if resource.class.respond_to?(:effective_resource) end # That class doesn't implement effective_resource do .. end block return [] unless effective_resource.present? # This is :id, all belongs_to ids, and model attributes permitted_params = effective_resource.permitted_attributes.select do |name, (_, atts)| if BLACKLIST.include?(name) false elsif name == :token # has_secure_token resource.respond_to?("regenerate_#{name}") == false elsif name == :site_id # acts_as_site_specific resource.class.respond_to?(:site_specific?) == false elsif atts.blank? || !atts.key?(:permitted) true # Default is true else permitted = (atts[:permitted].respond_to?(:call) ? Effective::ResourceExec.new(self, resource).instance_exec(&atts[:permitted]) : atts[:permitted]) if permitted == true || permitted == false || permitted == :array permitted elsif permitted == nil || permitted == :blank namespaces.length == 0 else # A symbol, string, or array of, representing the namespace (namespaces & Array(permitted).map(&:to_s)).present? end end end permitted_params = permitted_params.flat_map do |k, (datatype, v)| if datatype == :array [k, { k => [] }] elsif datatype == :permitted_param && k.to_s.ends_with?('_ids') { k => [] } elsif v.present? && v[:permitted] == :array [k, { k => [] }] elsif datatype == :permitted_param && v.present? && v.key?(:permitted_attributes) { k => v[:permitted_attributes] } elsif datatype == :effective_address { k => EffectiveAddresses.permitted_params } elsif datatype == :effective_assets EffectiveAssets.permitted_params else k end end # Recursively add any accepts_nested_resources effective_resource.nested_resources.each do |nested| if (nested_params = permitted_params_for(nested.klass, namespaces)).present? nested_params.insert(nested_params.rindex { |obj| !obj.kind_of?(Hash)} + 1, :_destroy) permitted_params << { "#{nested.name}_attributes".to_sym => nested_params } end end permitted_params end end end end
Nerian/effective_resources
app/models/effective/resources/naming.rb
<reponame>Nerian/effective_resources<filename>app/models/effective/resources/naming.rb<gh_stars>0 module Effective module Resources module Naming SPLIT = /\/|::/ # / or :: def name # 'post' @name ||= ((klass.present? ? klass.name : initialized_name).to_s.split(SPLIT).last || '').singularize.underscore end def plural_name # 'posts' name.pluralize end def initialized_name @initialized_name end def class_name # 'Effective::Post' @model_klass ? @model_klass.name : name.classify end def class_path # 'effective' class_name.split('::')[0...-1].map { |name| name.underscore } * '/' end def namespaced_class_name # 'Admin::Effective::Post' (Array(namespaces).map { |name| name.to_s.classify } + [class_name]) * '::' end def namespace # 'admin/things' (namespaces.join('/') if namespaces.present?) end def namespaces # ['admin', 'things'] @namespaces || [] end def human_name class_name.gsub('::', ' ').underscore.gsub('_', ' ') end def human_plural_name class_name.pluralize.gsub('::', ' ').underscore.gsub('_', ' ') end end end end
Nerian/effective_resources
app/controllers/concerns/effective/crud_controller/submits.rb
module Effective module CrudController module Submits extend ActiveSupport::Concern module ClassMethods # { 'Save' => { action: save, ...}} def submits @_effective_submits ||= effective_resource.submits end # { 'Approve' => { action: approve, ...}} def buttons @_effective_buttons ||= effective_resource.buttons end # { :approve => { redirect: .. }} def ons @_effective_ons ||= effective_resource.ons end # :only, :except, :if, :unless, :redirect, :success, :danger, :class def _insert_submit(action, label = nil, args = {}) raise 'expected args to be a Hash or false' unless args.kind_of?(Hash) || args == false if label == false submits.delete_if { |label, args| args[:action] == action }; return end if args == false submits.delete(label); return end if label # Overwrite the default member action when given a custom submit submits.delete_if { |label, args| args[:default] && args[:action] == action } end if args.key?(:if) && args[:if].respond_to?(:call) == false raise "expected if: to be callable. Try submit :approve, 'Save and Approve', if: -> { resource.finished? }" end if args.key?(:unless) && args[:unless].respond_to?(:call) == false raise "expected unless: to be callable. Try submit :approve, 'Save and Approve', unless: -> { resource.declined? }" end if args.key?(:only) args[:only] = Array(args[:only]) raise "expected only: to be a symbol or array of symbols. Try submit :approve, 'Save and Approve', only: [:edit]" unless args[:only].all? { |v| v.kind_of?(Symbol) } end if args.key?(:except) args[:except] = Array(args[:except]) raise "expected except: to be a symbol or array of symbols. Try submit :approve, 'Save and Approve', except: [:edit]" unless args[:except].all? { |v| v.kind_of?(Symbol) } end if args.key?(:redirect_to) # Normalize this option to redirect args[:redirect] = args.delete(:redirect_to) end args[:action] = action (submits[label] ||= {}).merge!(args) end def _insert_button(action, label = nil, args = {}) raise 'expected args to be a Hash or false' unless args.kind_of?(Hash) || args == false if label == false buttons.delete_if { |label, args| args[:action] == action }; return end if args == false buttons.delete(label); return end if label # Overwrite the default member action when given a custom label buttons.delete_if { |label, args| args[:default] && args[:action] == action } end if args.key?(:if) && args[:if].respond_to?(:call) == false raise "expected if: to be callable. Try button :approve, 'Approve', if: -> { resource.finished? }" end if args.key?(:unless) && args[:unless].respond_to?(:call) == false raise "expected unless: to be callable. Try button :approve, 'Approve', unless: -> { resource.declined? }" end if args.key?(:only) args[:only] = Array(args[:only]) raise "expected only: to be a symbol or array of symbols. Try button :approve, 'Save and Approve', only: [:edit]" unless args[:only].all? { |v| v.kind_of?(Symbol) } end if args.key?(:except) args[:except] = Array(args[:except]) raise "expected except: to be a symbol or array of symbols. Try button :approve, 'Save and Approve', except: [:edit]" unless args[:except].all? { |v| v.kind_of?(Symbol) } end if args.key?(:redirect_to) # Normalize this option to redirect args[:redirect] = args.delete(:redirect_to) end args[:action] = action (buttons[label] ||= {}).merge!(args) end def _insert_on(action, args = {}) raise 'expected args to be a Hash' unless args.kind_of?(Hash) if args.key?(:redirect_to) # Normalize this option to redirect args[:redirect] = args.delete(:redirect_to) end args[:action] = action (ons[action] ||= {}).merge!(args) end end end end end
Nerian/effective_resources
app/models/concerns/acts_as_archived.rb
# ActsAsArchived # # Implements the dumb archived pattern # An archived object should not be displayed on index screens, or any related resource's #new pages # effective_select (from the effective_bootstrap gem) is aware of this concern, and calls .unarchived and .archived appropriately when passed an ActiveRecord relation # Use the cascade argument to cascade archived changes to any has_manys # # class Thing < ApplicationRecord # has_many :comments # acts_as_archivable cascade: :comments # end # Each controller needs its own archive and unarchive action. # To simplify this, use the following route concern. # # In your routes.rb: # # Rails.application.routes.draw do # acts_as_archived # # resource :things, concern: :acts_as_archived # resource :comments, concern: :acts_as_archived # end # # and include Effective::CrudController in your resource controller module ActsAsArchived extend ActiveSupport::Concern module ActiveRecord def acts_as_archived(cascade: []) cascade = Array(cascade).compact if cascade.any? { |obj| !obj.kind_of?(Symbol) } raise 'expected cascade to be an Array of has_many symbols' end @acts_as_archived_options = { cascade: cascade } include ::ActsAsArchived end end module CanCan def acts_as_archived(klass) raise "klass does not implement acts_as_archived" unless klass.respond_to?(:acts_as_archived?) can(:archive, klass) { |obj| !obj.archived? } can(:unarchive, klass) { |obj| obj.archived? } end end module RoutesConcern def acts_as_archived concern :acts_as_archived do post :archive, on: :member post :unarchive, on: :member end end end included do scope :archived, -> { where(archived: true) } scope :unarchived, -> { where(archived: false) } effective_resource do archived :boolean, permitted: false end acts_as_archived_options = @acts_as_archived_options self.send(:define_method, :acts_as_archived_options) { acts_as_archived_options } end module ClassMethods def acts_as_archived?; true; end end # Instance methods def archive! transaction do update!(archived: true) # Runs validations acts_as_archived_options[:cascade].each { |obj| public_send(obj).update_all(archived: true) } end end def unarchive! transaction do update!(archived: false) acts_as_archived_options[:cascade].each { |obj| public_send(obj).update_all(archived: false) } end end def destroy archive! end end
Nerian/effective_resources
app/models/effective/resources/forms.rb
<reponame>Nerian/effective_resources module Effective module Resources module Forms # Used by datatables def search_form_field(name, type = nil) case (type || sql_type(name)) when :belongs_to { as: :select }.merge(search_form_field_collection(belongs_to(name))) when :belongs_to_polymorphic constant_pluralized = name.to_s.upcase constant = name.to_s.pluralize.upcase collection = (klass.const_get(constant) rescue nil) if defined?("#{klass.name}::#{constant}") collection ||= (klass.const_get(constant_pluralized) rescue nil) if defined?("#{klass.name}::#{constant_pluralized}") collection ||= {} { as: :select, polymorphic: true, collection: collection } when :has_and_belongs_to_many { as: :select }.merge(search_form_field_collection(has_and_belongs_to_many(name))) when :has_many { as: :select, multiple: true }.merge(search_form_field_collection(has_many(name))) when :has_one { as: :select, multiple: true }.merge(search_form_field_collection(has_one(name))) when :effective_addresses { as: :string } when :effective_roles { as: :select, collection: EffectiveRoles.roles } when :effective_obfuscation { as: :effective_obfuscation } when :boolean { as: :boolean, collection: [['Yes', true], ['No', false]] } when :datetime { as: :datetime } when :date { as: :date } when :integer { as: :number } when :text { as: :text } when :time { as: :time } when ActiveRecord::Base { as: :select }.merge(Effective::Resource.new(type).search_form_field_collection) else name = name.to_s # If the method is named :status, and there is a Class::STATUSES if ((klass || NilClass).const_defined?(name.pluralize.upcase) rescue false) { as: :select, collection: klass.const_get(name.pluralize.upcase) } elsif ((klass || NilClass).const_defined?(name.singularize.upcase) rescue false) { as: :select, collection: klass.const_get(name.singularize.upcase) } else { as: :string } end end end def search_form_field_collection(association = nil, max_id = 1000) res = (association.nil? ? self : Effective::Resource.new(association)) if res.max_id > max_id { as: :string } else if res.klass.unscoped.respond_to?(:datatables_scope) { collection: res.klass.datatables_scope.map { |obj| [obj.to_s, obj.to_param] } } elsif res.klass.unscoped.respond_to?(:datatables_filter) { collection: res.klass.datatables_filter.map { |obj| [obj.to_s, obj.to_param] } } elsif res.klass.unscoped.respond_to?(:sorted) { collection: res.klass.sorted.map { |obj| [obj.to_s, obj.to_param] } } else { collection: res.klass.all.map { |obj| [obj.to_s, obj.to_param] }.sort { |x, y| x[0] <=> y[0] } } end end end end end end
Nerian/effective_resources
app/models/effective/action_failed.rb
module Effective class ActionFailed < StandardError attr_reader :action, :subject def initialize(message = nil, action = nil, subject = nil) @message = message @action = action @subject = subject end def to_s @message || I18n.t(:'unauthorized.default', :default => 'Action Failed') end end end
Nerian/effective_resources
app/models/concerns/effective_resource.rb
# EffectiveResource # # Mark your model with 'effective_resource' module EffectiveResource extend ActiveSupport::Concern module ActiveRecord def effective_resource(options = nil, &block) return @_effective_resource unless block_given? include ::EffectiveResource @_effective_resource = Effective::Resource.new(self, &block) end end included do end module ClassMethods end end
Nerian/effective_resources
app/models/effective/resources/relation.rb
<filename>app/models/effective/resources/relation.rb module Effective module Resources module Relation def relation @relation ||= klass.where(nil) end # When Effective::Resource is initialized with an ActiveRecord relation, the following # methods will be available to operate on that relation, and be chainable and such # name: sort by this column, or this relation # sort: when a symbol or boolean, this is the relation's column to sort by def order(name, direction = :asc, as: nil, sort: nil, sql_column: nil, limit: nil, reorder: false) raise 'expected relation to be present' unless relation sql_column ||= sql_column(name) sql_type = (as || sql_type(name)) association = associated(name) sql_direction = sql_direction(direction) @relation = relation.reorder(nil) if reorder case sql_type when :belongs_to relation .order(Arel.sql("#{is_null(sql_column)} ASC")) .order(order_by_associated_conditions(association, sort: sort, direction: direction, limit: limit)) when :belongs_to_polymorphic relation .order(Arel.sql("#{sql_column}_type #{sql_direction}")) .order(Arel.sql("#{sql_column}_id #{sql_direction}")) when :has_and_belongs_to_many, :has_many, :has_one relation .order(order_by_associated_conditions(association, sort: sort, direction: direction, limit: limit)) .order(Arel.sql("#{sql_column(klass.primary_key)} #{sql_direction}")) when :effective_addresses relation .order(order_by_associated_conditions(associated(:addresses), sort: sort, direction: direction, limit: limit)) .order(Arel.sql("#{sql_column(klass.primary_key)} #{sql_direction}")) when :effective_roles relation.order(Arel.sql("#{sql_column(:roles_mask)} #{sql_direction}")) when :string, :text relation .order(Arel.sql(("ISNULL(#{sql_column}), " if mysql?).to_s + "#{sql_column}='' ASC, #{sql_column} #{sql_direction}" + (" NULLS LAST" if postgres?).to_s)) when :time relation .order(Arel.sql(("ISNULL(#{sql_column}), " if mysql?).to_s + "EXTRACT(hour from #{sql_column}) #{sql_direction}, EXTRACT(minute from #{sql_column}) #{sql_direction}" + (" NULLS LAST" if postgres?).to_s)) else relation .order(Arel.sql(("ISNULL(#{sql_column}), " if mysql?).to_s + "#{sql_column} #{sql_direction}" + (" NULLS LAST" if postgres?).to_s)) end end def search(name, value, as: nil, fuzzy: true, sql_column: nil) raise 'expected relation to be present' unless relation sql_column ||= sql_column(name) sql_type = (as || sql_type(name)) fuzzy = true unless fuzzy == false if ['SUM(', 'COUNT(', 'MAX(', 'MIN(', 'AVG('].any? { |str| sql_column.to_s.include?(str) } return relation.having("#{sql_column} = ?", value) end association = associated(name) term = Effective::Attribute.new(sql_type, klass: (association.try(:klass) rescue nil) || klass).parse(value, name: name) # term == 'nil' rescue false is a Rails 4.1 fix, where you can't compare a TimeWithZone to 'nil' if (term == 'nil' rescue false) && ![:has_and_belongs_to_many, :has_many, :has_one, :belongs_to_polymorphic, :effective_roles].include?(sql_type) return relation.where(is_null(sql_column)) end case sql_type when :belongs_to, :has_and_belongs_to_many, :has_many, :has_one relation.where(search_by_associated_conditions(association, term, fuzzy: fuzzy)) when :belongs_to_polymorphic (type, id) = term.split('_') if term == 'nil' relation.where(is_null("#{sql_column}_id")).where(is_null("#{sql_column}_type")) elsif type.present? && id.present? relation.where("#{sql_column}_id = ?", id).where("#{sql_column}_type = ?", type) else id ||= Effective::Attribute.new(:integer).parse(term) relation.where("#{sql_column}_id = ? OR #{sql_column}_type = ?", id, (type || term)) end when :effective_addresses relation.where(id: Effective::Resource.new(association).search_any(value, fuzzy: fuzzy).pluck(:addressable_id)) when :effective_obfuscation # If value == term, it's an invalid deobfuscated id relation.where("#{sql_column} = ?", (value == term ? 0 : term)) when :effective_roles relation.with_role(term) when :boolean relation.where("#{sql_column} = ?", term) when :datetime, :date end_at = ( case (value.to_s.scan(/(\d+)/).flatten).length when 1 ; term.end_of_year # Year when 2 ; term.end_of_month # Year-Month when 3 ; term.end_of_day # Year-Month-Day when 4 ; term.end_of_hour # Year-Month-Day Hour when 5 ; term.end_of_minute # Year-Month-Day Hour-Minute when 6 ; term + 1.second # Year-Month-Day Hour-Minute-Second else term end ) relation.where("#{sql_column} >= ? AND #{sql_column} <= ?", term, end_at) when :time timed = relation.where("EXTRACT(hour from #{sql_column}) = ?", term.utc.hour) timed = timed.where("EXTRACT(minute from #{sql_column}) = ?", term.utc.min) if term.min > 0 timed when :decimal, :currency if fuzzy && (term.round(0) == term) && value.to_s.include?('.') == false if term < 0 relation.where("#{sql_column} <= ? AND #{sql_column} > ?", term, term-1.0) else relation.where("#{sql_column} >= ? AND #{sql_column} < ?", term, term+1.0) end else relation.where("#{sql_column} = ?", term) end when :duration if fuzzy && (term % 60 == 0) && value.to_s.include?('m') == false if term < 0 relation.where("#{sql_column} <= ? AND #{sql_column} > ?", term, term-60) else relation.where("#{sql_column} >= ? AND #{sql_column} < ?", term, term+60) end else relation.where("#{sql_column} = ?", term) end when :integer relation.where("#{sql_column} = ?", term) when :percent relation.where("#{sql_column} = ?", term) when :price relation.where("#{sql_column} = ?", term) when :string, :text, :email if fuzzy relation.where("#{sql_column} #{ilike} ?", "%#{term}%") else relation.where("#{sql_column} = ?", term) end else raise "unsupported sql type #{sql_type}" end end def search_any(value, columns: nil, fuzzy: nil) raise 'expected relation to be present' unless relation # Assume this is a set of IDs if value.kind_of?(Integer) || value.kind_of?(Array) || (value.to_i.to_s == value) return relation.where(klass.primary_key => value) end # Otherwise, we fall back to a string/text search of all columns columns = Array(columns || search_columns) fuzzy = true unless fuzzy == false conditions = ( if fuzzy columns.map { |name| "#{sql_column(name)} #{ilike} :fuzzy" } else columns.map { |name| "#{sql_column(name)} = :value" } end ).join(' OR ') relation.where(conditions, fuzzy: "%#{value}%", value: value) end private def search_by_associated_conditions(association, value, fuzzy: nil) resource = Effective::Resource.new(association) # Search the target model for its matching records / keys relation = resource.search_any(value, fuzzy: fuzzy) if association.options[:as] # polymorphic relation = relation.where(association.type => klass.name) end # key: the id, or associated_id on my table # keys: the ids themselves as per the target table if association.macro == :belongs_to key = sql_column(association.foreign_key) keys = relation.pluck(association.klass.primary_key) elsif association.macro == :has_and_belongs_to_many key = sql_column(klass.primary_key) values = relation.pluck(association.source_reflection.klass.primary_key).uniq.compact keys = if value == 'nil' klass.where.not(klass.primary_key => klass.joins(association.name)).pluck(klass.primary_key) else klass.joins(association.name) .where(association.name => { association.source_reflection.klass.primary_key => values }) .pluck(klass.primary_key) end elsif association.options[:through].present? scope = association.through_reflection.klass.all if association.source_reflection.options[:polymorphic] reflected_klass = association.klass scope = scope.where(association.source_reflection.foreign_type => reflected_klass.name) else reflected_klass = association.source_reflection.klass end if association.through_reflection.macro == :belongs_to key = association.through_reflection.foreign_key pluck_key = association.through_reflection.klass.primary_key else key = sql_column(klass.primary_key) pluck_key = association.through_reflection.foreign_key end if value == 'nil' keys = klass.where.not(klass.primary_key => scope.pluck(pluck_key)).pluck(klass.primary_key) else keys = scope.where(association.source_reflection.foreign_key => relation).pluck(pluck_key) end elsif association.macro == :has_many key = sql_column(klass.primary_key) keys = if value == 'nil' klass.where.not(klass.primary_key => resource.klass.pluck(association.foreign_key)).pluck(klass.primary_key) else relation.pluck(association.foreign_key) end elsif association.macro == :has_one key = sql_column(klass.primary_key) keys = if value == 'nil' klass.where.not(klass.primary_key => resource.klass.pluck(association.foreign_key)).pluck(klass.primary_key) else relation.pluck(association.foreign_key) end end "#{key} IN (#{(keys.uniq.compact.presence || [0]).join(',')})" end def order_by_associated_conditions(association, sort: nil, direction: :asc, limit: nil) resource = Effective::Resource.new(association) # Order the target model for its matching records / keys sort_column = (sort unless sort == true) || resource.sort_column relation = resource.order(sort_column, direction, limit: limit, reorder: true).limit(1500) if association.options[:as] # polymorphic relation = relation.where(association.type => klass.name) end # key: the id, or associated_id on my table # keys: the ids themselves as per the target table if association.macro == :belongs_to key = sql_column(association.foreign_key) keys = relation.pluck(association.klass.primary_key) elsif association.macro == :has_and_belongs_to_many key = sql_column(klass.primary_key) source = "#{association.join_table}.#{association.source_reflection.association_foreign_key}" values = relation.pluck(association.source_reflection.klass.primary_key).uniq.compact # The searched keys keys = klass.joins(association.name) .order(values.uniq.compact.map { |value| "#{source}=#{value} DESC" }.join(',')) .pluck(klass.primary_key) elsif association.macro == :has_many && association.options[:through].present? key = sql_column(klass.primary_key) source = association.source_reflection.foreign_key values = relation.pluck(association.source_reflection.klass.primary_key).uniq.compact # The searched keys keys = association.through_reflection.klass .order(values.uniq.compact.map { |value| "#{source}=#{value} DESC" }.join(',')) .pluck(association.through_reflection.foreign_key) elsif association.macro == :has_many key = sql_column(klass.primary_key) keys = relation.pluck(association.foreign_key) elsif association.macro == :has_one key = sql_column(klass.primary_key) keys = relation.pluck(association.foreign_key) end Arel.sql(keys.uniq.compact.map { |value| "#{key}=#{value} DESC" }.join(',')) end end end end
Nerian/effective_resources
app/models/effective/resources/instance.rb
module Effective module Resources module Instance attr_accessor :instance # This is written for use by effective_logging and effective_trash BLACKLIST = [:logged_changes, :trash] def instance @instance || klass.new end # called by effective_trash and effective_logging def instance_attributes(only: nil, except: nil) return {} unless instance.present? # Build up our only and except only = Array(only).map(&:to_sym) except = Array(except).map(&:to_sym) + BLACKLIST # Simple Attributes attributes = { attributes: instance.attributes.symbolize_keys } attributes[:attributes] = attributes[:attributes].except(*except) if except.present? attributes[:attributes] = attributes[:attributes].slice(*only) if only.present? # Collect to_s representations of all belongs_to associations belong_tos.each do |association| next if except.present? && except.include?(association.name) next unless only.blank? || only.include?(association.name) attributes[association.name] = instance.send(association.name).to_s end # Grab the instance attributes of each nested resource nested_resources.each do |association| next if except.present? && except.include?(association.name) next unless only.blank? || only.include?(association.name) next if association.options[:through] attributes[association.name] ||= {} Array(instance.send(association.name)).each_with_index do |child, index| next unless child.present? resource = Effective::Resource.new(child) attributes[association.name][index] = resource.instance_attributes(only: only, except: except) end end has_ones.each do |association| next if except.present? && except.include?(association.name) next unless only.blank? || only.include?(association.name) attributes[association.name] = instance.send(association.name).to_s end has_manys.each do |association| next if except.present? && except.include?(association.name) next unless only.blank? || only.include?(association.name) next if BLACKLIST.include?(association.name) attributes[association.name] = instance.send(association.name).map { |obj| obj.to_s } end has_and_belongs_to_manys.each do |association| next if except.present? && except.include?(association.name) next unless only.blank? || only.include?(association.name) attributes[association.name] = instance.send(association.name).map { |obj| obj.to_s } end attributes.delete_if { |_, value| value.blank? } end # used by effective_logging def instance_changes(only: nil, except: nil) return {} unless (instance.present? && instance.previous_changes.present?) # Build up our only and except only = Array(only).map(&:to_sym) except = Array(except).map(&:to_sym) + BLACKLIST changes = instance.previous_changes.symbolize_keys.delete_if do |attribute, (before, after)| begin (before.kind_of?(ActiveSupport::TimeWithZone) && after.kind_of?(ActiveSupport::TimeWithZone) && before.to_i == after.to_i) || (before == nil && after == false) || (before == nil && after == ''.freeze) rescue => e true end end changes = changes.except(*except) if except.present? changes = changes.slice(*only) if only.present? # Log to_s changes on all belongs_to associations belong_tos.each do |association| next if except.present? && except.include?(association.name) next unless only.blank? || only.include?(association.name) if (change = changes.delete(association.foreign_key)).present? changes[association.name] = [(association.klass.find_by_id(change.first) if changes.first), instance.send(association.name)] end end changes end end end end
Nerian/effective_resources
app/models/concerns/acts_as_slugged.rb
# ActsAsSlugged # # This module automatically generates slugs based on the :to_s field using a before_validation filter # # Mark your model with 'acts_as_sluggable' make sure you have a string field :slug module ActsAsSlugged extend ActiveSupport::Concern module ActiveRecord def acts_as_slugged(options = nil) include ::ActsAsSlugged end end included do extend FinderMethods before_validation { self.slug ||= build_slug } validates :slug, presence: true, uniqueness: true, exclusion: { in: excluded_slugs }, length: { maximum: 255 }, format: { with: /\A[a-zA-Z0-9_-]*\z/, message: 'only _ and - symbols allowed. no spaces either.' } end module ClassMethods def relation super.tap { |relation| relation.extend(FinderMethods) } end def excluded_slugs ::ActiveRecord::Base.connection.tables.map { |x| x }.compact end end module FinderMethods def find(*args) return super unless args.length == 1 return super if block_given? where(slug: args.first).or(where(id: args.first)).first || raise(::ActiveRecord::RecordNotFound.new("Couldn't find #{name} with 'slug'=#{args.first}")) end end # Instance Methods def build_slug slug = self.to_s.parameterize.downcase[0, 250] if self.class.excluded_slugs.include?(slug) slug = "#{slug}-#{self.class.name.demodulize.parameterize}" end if (count = self.class.where(slug: slug).count) > 0 slug = "#{slug}-#{count+1}" end slug end def to_param slug end end
Nerian/effective_resources
app/models/effective/code_reader.rb
<reponame>Nerian/effective_resources module Effective class CodeReader attr_reader :lines def initialize(filename, &block) @lines = File.open(filename).readlines block.call(self) if block_given? end # Iterate over the lines with a depth, and passed the stripped line to the passed block def each_with_depth(from: nil, to: nil, &block) Array(lines).each_with_index do |line, index| next if index < (from || 0) depth = line.length - line.lstrip.length block.call(line.strip, depth, index) break if to == index end nil end # Returns the index of the first line where the passed block returns true def index(from: nil, to: nil, &block) each_with_depth(from: from, to: to) do |line, depth, index| return index if block.call(line, depth, index) end end # Returns the stripped contents of the line in which the passed block returns true def first(from: nil, to: nil, &block) each_with_depth(from: from, to: to) do |line, depth, index| return line if block.call(line, depth, index) end end alias_method :find, :first # Returns the stripped contents of the last line where the passed block returns true def last(from: nil, to: nil, &block) retval = nil each_with_depth(from: from, to: nil) do |line, depth, index| retval = line if block.call(line, depth, index) end retval end # Returns an array of stripped lines for each line where the passed block returns true def select(from: nil, to: nil, &block) retval = [] each_with_depth(from: from, to: to) do |line, depth, index| retval << line if (block_given? == false || block.call(line, depth, index)) end retval end end end
Nerian/effective_resources
app/models/effective/resources/init.rb
module Effective module Resources module Init private def _initialize_input(input, namespace: nil) @initialized_name = input @model_klass = case input when String, Symbol _klass_by_name(input) when Class input when ActiveRecord::Relation input.klass when (ActiveRecord::Reflection::AbstractReflection rescue :nil) ((input.klass rescue nil).presence || _klass_by_name(input.class_name)) unless input.options[:polymorphic] when ActiveRecord::Reflection::MacroReflection ((input.klass rescue nil).presence || _klass_by_name(input.class_name)) unless input.options[:polymorphic] when ActionDispatch::Journey::Route @initialized_name = input.defaults[:controller] _klass_by_name(input.defaults[:controller]) when nil ; raise 'expected a string or class' else ; _klass_by_name(input.class.name) end if namespace @namespaces = (namespace.kind_of?(String) ? namespace.split('/') : Array(namespace)) end if input.kind_of?(ActiveRecord::Relation) @relation = input end if input.kind_of?(ActiveRecord::Reflection::MacroReflection) && input.scope @relation = klass.where(nil).merge(input.scope) end if klass && input.instance_of?(klass) @instance = input end end def _klass_by_name(input) input = input.to_s input = input[1..-1] if input.start_with?('/') names = input.split('/') 0.upto(names.length-1) do |index| class_name = (names[index..-1].map { |name| name.classify } * '::') klass = class_name.safe_constantize if klass.present? @namespaces ||= names[0...index] @model_klass = klass return klass end end nil end # Lazy initialized def _initialize_written @written_attributes = [] @written_belong_tos = [] @written_scopes = [] return unless File.exists?(model_file) Effective::CodeReader.new(model_file) do |reader| first = reader.index { |line| line == '# Attributes' } last = reader.index(from: first) { |line| line.start_with?('#') == false && line.length > 0 } if first if first && last @written_attributes = reader.select(from: first+1, to: last-1).map do |line| Effective::Attribute.parse_written(line).presence end.compact end @written_belong_tos = reader.select { |line| line.start_with?('belongs_to ') }.map do |line| line.scan(/belongs_to\s+:(\w+)/).flatten.first end @written_scopes = reader.select { |line| line.start_with?('scope ') }.map do |line| line.scan(/scope\s+:(\w+)/).flatten.first end end end end end end
Nerian/effective_resources
app/models/effective/resources/actions.rb
<filename>app/models/effective/resources/actions.rb module Effective module Resources module Actions # This was written for the Edit actions fallback templates and Datatables # Effective::Resource.new('admin/posts').routes[:index] def routes @routes ||= ( matches = [[namespace, plural_name].compact.join('/'.freeze), [namespace, name].compact.join('/'.freeze)] routes_engine.routes.routes.select do |route| matches.any? { |match| match == route.defaults[:controller] } end.inject({}) do |h, route| h[route.defaults[:action].to_sym] = route; h end ) end # Effective::Resource.new('effective/order', namespace: :admin) def routes_engine case class_name when 'Effective::Order'.freeze EffectiveOrders::Engine else Rails.application end end # Effective::Resource.new('admin/posts').action_path_helper(:edit) => 'edit_admin_posts_path' # This will return empty for create, update and destroy def action_path_helper(action) return unless routes[action] return (routes[action].name + '_path'.freeze) if routes[action].name.present? end # Effective::Resource.new('admin/posts').action_path(:edit, Post.last) => '/admin/posts/3/edit' # Will work for any action. Returns the real path def action_path(action, resource = nil, opts = {}) if klass.nil? && resource.present? && initialized_name.kind_of?(ActiveRecord::Reflection::BelongsToReflection) return Effective::Resource.new(resource, namespace: namespace).action_path(action, resource, opts) end return unless routes[action] if resource.kind_of?(Hash) opts = resource; resource = nil end # edge case: Effective::Resource.new('admin/comments').action_path(:new, @post) if resource && klass && !resource.kind_of?(klass) if (bt = belongs_to(resource)).present? && instance.respond_to?("#{bt.name}=") return routes[action].format(klass.new(bt.name => resource)).presence end end # This generates the correct route when an object is overriding to_param if (resource || instance).respond_to?(:attributes) formattable = (resource || instance).attributes.symbolize_keys.merge(id: (resource || instance).to_param) end path = routes[action].format(formattable || {}).presence if path.present? && opts.present? uri = URI.parse(path) uri.query = URI.encode_www_form(opts) path = uri.to_s end path end def actions routes.keys end def crud_actions actions & %i(index new create show edit update destroy) end # GET actions def collection_actions routes.values.map { |route| route.defaults[:action].to_sym if is_collection_route?(route) }.compact end def collection_get_actions routes.values.map { |route| route.defaults[:action].to_sym if is_collection_route?(route) && is_get_route?(route) }.compact end def collection_post_actions routes.values.map { |route| route.defaults[:action].to_sym if is_collection_route?(route) && is_post_route?(route) }.compact end # All actions def member_actions routes.values.map { |route| route.defaults[:action].to_sym if is_member_route?(route) }.compact end # GET actions def member_get_actions routes.values.map { |route| route.defaults[:action].to_sym if is_member_route?(route) && is_get_route?(route) }.compact end def member_delete_actions routes.values.map { |route| route.defaults[:action].to_sym if is_member_route?(route) && is_delete_route?(route) }.compact end # POST/PUT/PATCH actions def member_post_actions routes.values.map { |route| route.defaults[:action].to_sym if is_member_route?(route) && is_post_route?(route) }.compact end # Same as controller_path in the view def controller_path [namespace, plural_name].compact * '/'.freeze end private def is_member_route?(route) (route.path.required_names || []).include?('id'.freeze) end def is_collection_route?(route) (route.path.required_names || []).include?('id'.freeze) == false end def is_get_route?(route) route.verb.to_s.include?('GET'.freeze) end def is_delete_route?(route) route.verb.to_s.include?('DELETE'.freeze) end def is_post_route?(route) ['POST', 'PUT', 'PATCH'].freeze.any? { |verb| route.verb == verb } end end end end
Nerian/effective_resources
app/controllers/concerns/effective/flash_messages.rb
<filename>app/controllers/concerns/effective/flash_messages.rb module Effective module FlashMessages extend ActiveSupport::Concern # flash[:success] = flash_success(@post) def flash_success(resource, action = nil, name: nil) raise 'expected an ActiveRecord resource' unless (name || resource.class.respond_to?(:model_name)) "Successfully #{action_verb(action)} #{name || resource}".html_safe end # flash.now[:danger] = flash_danger(@post) def flash_danger(resource, action = nil, e: nil, name: nil) raise 'expected an ActiveRecord resource' unless resource.respond_to?(:errors) && (name || resource.class.respond_to?(:model_name)) action ||= resource.respond_to?(:new_record?) ? (resource.new_record? ? :create : :update) : :save action = action.to_s.gsub('_', ' ') messages = flash_errors(resource, e: e) name ||= resource.to_s.presence ["Unable to #{action}", (" #{name}" if name), (": #{messages}" if messages)].compact.join.html_safe end # flash.now[:danger] = "Unable to accept: #{flash_errors(@post)}" def flash_errors(resource, e: nil) raise 'expected an ActiveRecord resource' unless resource.respond_to?(:errors) messages = resource.errors.map do |attribute, message| if message[0] == message[0].upcase # If the error begins with a capital letter message elsif attribute == :base message elsif attribute.to_s.end_with?('_ids') "#{resource.class.human_attribute_name(attribute.to_s[0..-5].pluralize).downcase} #{message}" else "#{resource.class.human_attribute_name(attribute).downcase} #{message}" end end messages << e.message if messages.blank? && e && e.respond_to?(:message) messages.to_sentence.presence end def action_verb(action) action = action.to_s.gsub('_', ' ') word = action.split(' ').first.to_s if word == 'destroy' 'deleted' elsif word == 'undo' 'undid' elsif word.end_with?('e') action.sub(word, word + 'd') elsif ['a', 'i', 'o', 'u'].include?(word[-1]) action else action.sub(word, word + 'ed') end end end end
Nerian/effective_resources
app/models/effective/resources/sql.rb
module Effective module Resources module Sql def column(name) name = name.to_s columns.find { |col| col.name == name || (belongs_to(name) && col.name == belongs_to(name).foreign_key) } end def columns klass.columns end def column_names @column_names ||= columns.map { |col| col.name } end def table klass.unscoped.table end def max_id return 999999 unless klass.respond_to?(:unscoped) @max_id ||= klass.unscoped.maximum(klass.primary_key).to_i end def sql_column(name) column = column(name) return nil unless table && column [klass.connection.quote_table_name(table.name), klass.connection.quote_column_name(column.name)].join('.') end def sql_direction(name) name.to_s.downcase == 'desc' ? 'DESC'.freeze : 'ASC'.freeze end # This is for EffectiveDatatables (col as:) # Might be :name, or 'users.name' def sql_type(name) name = name.to_s.split('.').first if belongs_to(name) :belongs_to elsif (column = column(name)) column.type elsif has_many(name) :has_many elsif has_one(name) :has_one elsif belongs_to_polymorphic(name) :belongs_to_polymorphic elsif has_and_belongs_to_many(name) :has_and_belongs_to_many elsif name == 'id' && defined?(EffectiveObfuscation) && klass.respond_to?(:deobfuscate) :effective_obfuscation elsif name == 'roles' && defined?(EffectiveRoles) && klass.respond_to?(:with_role) :effective_roles elsif (name.include?('_address') || name.include?('_addresses')) && defined?(EffectiveAddresses) && (klass.new rescue nil).respond_to?(:effective_addresses) :effective_addresses elsif name.ends_with?('_id') :integer else :string end end # This tries to figure out the column we should order this collection by. # Whatever would match up with the .to_s # Unless it's set from outside by datatables... def sort_column return @_sort_column if @_sort_column ['name', 'title', 'label', 'subject', 'full_name', 'first_name', 'email', 'description'].each do |name| return name if column_names.include?(name) end klass.primary_key end def sort_column=(name) raise "unknown sort column: #{name}" unless column_names.include?(name) @_sort_column = name end # Any string or text columns # TODO: filter out _type columns for polymorphic def search_columns return @_search_columns if @_search_columns columns.map { |column| column.name if [:string, :text].include?(column.type) }.compact end def search_columns=(name) names = Array(name) names.each { |name| raise "unknown search column: #{name}" unless column_names.include?(name) } @_search_columns = names end def ilike @ilike ||= (postgres? ? 'ILIKE' : 'LIKE') # Only Postgres supports ILIKE, Mysql and Sqlite3 use LIKE end def postgres? return @postgres unless @postgres.nil? @postgres ||= (klass.connection.kind_of?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) rescue false) end def mysql? return @mysql unless @mysql.nil? @mysql ||= (klass.connection.kind_of?(ActiveRecord::ConnectionAdapters::Mysql2Adapter) rescue false) end def is_null(sql_column) mysql? == true ? "ISNULL(#{sql_column})" : "#{sql_column} IS NULL" end end end end
Nerian/effective_resources
lib/generators/effective_resources/install_generator.rb
<filename>lib/generators/effective_resources/install_generator.rb module EffectiveResources module Generators class InstallGenerator < Rails::Generators::Base desc 'Creates an EffectiveResources initializer in your application.' source_root File.expand_path('../../templates', __FILE__) def copy_initializer template ('../' * 3) + 'config/effective_resources.rb', 'config/initializers/effective_resources.rb' end def copy_application_templates [:edit, :index, :new, :show].each do |file| template ('../' * 3) + "app/views/application/#{file}.html.haml", "app/views/application/#{file}.html.haml" end end end end end
Nerian/effective_resources
app/controllers/concerns/effective/crud_controller.rb
<reponame>Nerian/effective_resources module Effective module CrudController extend ActiveSupport::Concern include Effective::CrudController::Actions include Effective::CrudController::Paths include Effective::CrudController::PermittedParams include Effective::CrudController::Respond include Effective::CrudController::Save include Effective::CrudController::Submits included do define_actions_from_routes define_permitted_params_from_model define_callbacks :resource_render, :resource_before_save, :resource_after_save, :resource_error end module ClassMethods include Effective::CrudController::Dsl def effective_resource @_effective_resource ||= Effective::Resource.new(controller_path) end # Automatically respond to any action defined via the routes file def define_actions_from_routes (effective_resource.member_actions - effective_resource.crud_actions).each do |action| define_method(action) { member_action(action) } end (effective_resource.collection_actions - effective_resource.crud_actions).each do |action| define_method(action) { collection_action(action) } end end def define_permitted_params_from_model if effective_resource.model.present? define_method(:effective_resource_permitted_params) { resource_permitted_params } # save.rb end if effective_resource.active_model? define_method(:effective_resource_permitted_params) { resource_active_model_permitted_params } # save.rb end end end def resource # @thing instance_variable_get("@#{resource_name}") end def resource=(instance) instance_variable_set("@#{resource_name}", instance) end def resources # @things send(:instance_variable_get, "@#{resource_plural_name}") end def resources=(instance) send(:instance_variable_set, "@#{resource_plural_name}", instance) end def effective_resource self.class.effective_resource end private def resource_name # 'thing' effective_resource.name end def resource_klass # Thing effective_resource.klass end def resource_plural_name # 'things' effective_resource.plural_name end # Returns an ActiveRecord relation based on the computed value of `resource_scope` dsl method def resource_scope # Thing @_effective_resource_relation ||= ( relation = case @_effective_resource_scope # If this was initialized by the resource_scope before_filter when ActiveRecord::Relation @_effective_resource_scope when Hash effective_resource.klass.where(@_effective_resource_scope) when Symbol effective_resource.klass.send(@_effective_resource_scope) when nil effective_resource.klass.respond_to?(:all) ? effective_resource.klass.all : effective_resource.klass else raise "expected resource_scope method to return an ActiveRecord::Relation or Hash" end unless relation.kind_of?(ActiveRecord::Relation) || effective_resource.active_model? raise("unable to build resource_scope for #{effective_resource.klass || 'unknown klass'}. Please name your controller to match an existing model, or manually define a resource_scope.") end relation ) end def resource_datatable_attributes resource_scope.where_values_hash.symbolize_keys end def resource_datatable(action) datatable_klass = if action == :index effective_resource.datatable_klass else # Admin::ActionDatatable.new "#{[effective_resource.namespace.to_s.classify.presence, action.to_s.classify].compact.join('::')}Datatable".safe_constantize || "#{[effective_resource.namespace.to_s.classify.presence, action.to_s.pluralize.classify].compact.join('::')}Datatable".safe_constantize || "#{[effective_resource.namespace.to_s.classify.presence, action.to_s.singularize.classify].compact.join('::')}Datatable".safe_constantize end return unless datatable_klass.present? datatable = datatable_klass.new(resource_datatable_attributes) datatable.view = view_context datatable end def resource_params_method_name ["#{resource_name}_params", "#{resource_plural_name}_params", 'permitted_params', 'effective_resource_permitted_params', ('resource_permitted_params' if effective_resource.model.present?)].compact.find { |name| respond_to?(name, true) } || 'params' end end end
Nerian/effective_resources
app/models/effective/attribute.rb
<filename>app/models/effective/attribute.rb<gh_stars>0 module Effective class Attribute attr_accessor :name, :type, :klass # This parses the written attributes def self.parse_written(input) input = input.to_s if (scanned = input.scan(/^\W*(\w+)\W*:(\w+)/).first).present? new(*scanned) end end # This kind of follows the rails GeneratedAttribute method. # In that case it will be initialized with a name and a type. # We also use this class to do value parsing in Datatables. # In that case it will be initialized with just a 'name' def initialize(obj, type = nil, klass: nil) @klass = klass if obj.present? && type.present? @name = obj.to_s @type = type.to_sym end @type ||= ( case obj when :boolean ; :boolean when :currency ; :currency when :date ; :date when :datetime ; :datetime when :decimal ; :decimal when :duration ; :duration when :email ; :email when :integer ; :integer when :percent ; :percent when :percentage ; :percent when :phone ; :phone when :price ; :price when :nil ; :nil when :resource ; :resource when :string ; :string when :text ; :text when :time ; :time when FalseClass ; :boolean when (defined?(Integer) ? Integer : Fixnum) ; :integer when Float ; :decimal when NilClass ; :nil when String ; :string when TrueClass ; :boolean when ActiveSupport::TimeWithZone ; :datetime when Date ; :date when ActiveRecord::Base ; :resource when :belongs_to ; :belongs_to when :belongs_to_polymorphic ; :belongs_to_polymorphic when :has_many ; :has_many when :has_and_belongs_to_many ; :has_and_belongs_to_many when :has_one ; :has_one when :effective_addresses ; :effective_addresses when :effective_obfuscation ; :effective_obfuscation when :effective_roles ; :effective_roles else raise "unsupported type for #{obj}" end ) end def parse(value, name: nil) case type when :boolean [true, 'true', 't', '1'].include?(value) when :date, :datetime if (digits = value.to_s.scan(/(\d+)/).flatten).present? date = if digits.first.length == 4 # 2017-01-10 Time.zone.local(*digits) else # 01/10/2016 year = digits.find { |d| d.length == 4} digits = [year] + (digits - [year]) Time.zone.local(*digits) end name.to_s.start_with?('end_') ? date.end_of_day : date end when :time if (digits = value.to_s.scan(/(\d+)/).flatten).present? now = Time.zone.now Time.zone.local(now.year, now.month, now.day, *digits) end when :decimal, :currency (value.kind_of?(String) ? value.gsub(/[^0-9|\-|\.]/, '') : value).to_f when :duration if value.to_s.include?('h') (hours, minutes) = (value.to_s.gsub(/[^0-9|\-|h]/, '').split('h')) (hours.to_i * 60) + ((hours.to_i < 0) ? -(minutes.to_i) : minutes.to_i) else value.to_s.gsub(/[^0-9|\-|h]/, '').to_i end when :effective_obfuscation klass.respond_to?(:deobfuscate) ? klass.deobfuscate(value) : value.to_s when :effective_roles EffectiveRoles.roles.include?(value.to_sym) ? value : EffectiveRoles.roles_for(value) when :integer (value.kind_of?(String) ? value.gsub(/\D/, '') : value).to_i when :percent # Integer * 1000. Percentage to 3 digits. value.kind_of?(Integer) ? value : (value.to_s.gsub(/[^0-9|\-|\.]/, '').to_f * 1000.0).round when :phone digits = value.to_s.gsub(/\D/, '').chars digits = (digits.first == '1' ? digits[1..10] : digits[0..9]) # Throw away a leading 1 return nil unless digits.length == 10 "(#{digits[0..2].join}) #{digits[3..5].join}-#{digits[6..10].join}" when :integer (value.kind_of?(String) ? value.gsub(/\D/, '') : value).to_i when :nil value.presence when :price # Integer * 100. Number of cents. value.kind_of?(Integer) ? value : (value.to_s.gsub(/[^0-9|\-|\.]/, '').to_f * 100.0).round when :string, :text, :email value.to_s when :belongs_to_polymorphic value.to_s when :belongs_to, :has_many, :has_and_belongs_to_many, :has_one, :resource, :effective_addresses # Returns an Array of ints, an Int or String if value.kind_of?(Integer) || value.kind_of?(Array) value else digits = value.to_s.gsub(/[^0-9|,]/, '') # '87' or '87,254,300' or 'something' if digits == value || digits.length == 10 if klass.respond_to?(:deobfuscate) digits.split(',').map { |str| klass.deobfuscate(str).to_i } else digits.split(',').map { |str| str.to_i } end else value.to_s end end else raise "unsupported type #{type}" end end def to_s name end def present? name.present? || type.present? end def human_name name.humanize end def <=>(other) name <=> other.name end def ==(other) name == other.name && type == other.type end end end
Nerian/effective_resources
app/models/effective/resource.rb
<gh_stars>0 module Effective class Resource include Effective::Resources::Actions include Effective::Resources::Associations include Effective::Resources::Attributes include Effective::Resources::Controller include Effective::Resources::Init include Effective::Resources::Instance include Effective::Resources::Forms include Effective::Resources::Klass include Effective::Resources::Model include Effective::Resources::Naming include Effective::Resources::Paths include Effective::Resources::Relation include Effective::Resources::Sql # post, Post, Admin::Post, admin::Post, admin/posts, admin/post, admin/effective::post def initialize(input, namespace: nil, &block) _initialize_input(input, namespace: namespace) _initialize_model(&block) if block_given? self end def to_s name end end end
Nerian/effective_resources
lib/effective_resources/engine.rb
module EffectiveResources class Engine < ::Rails::Engine engine_name 'effective_resources' config.autoload_paths += Dir["#{config.root}/lib/", "#{config.root}/app/controllers/concerns/effective/"] # Set up our default configuration options. initializer 'effective_resources.defaults', before: :load_config_initializers do |app| eval File.read("#{config.root}/config/effective_resources.rb") end # Register the acts_as_archived routes concern # resources :things, concerns: :acts_as_archived initializer 'effective_resources.routes_concern' do |app| ActionDispatch::Routing::Mapper.include(ActsAsArchived::RoutesConcern) end # Register the flash_messages concern so that it can be called in ActionController initializer 'effective_resources.action_controller' do |app| ActiveSupport.on_load :action_controller do include(Effective::FlashMessages) end end # Include acts_as_addressable concern and allow any ActiveRecord object to call it initializer 'effective_resources.active_record' do |app| ActiveSupport.on_load :active_record do ActiveRecord::Base.extend(ActsAsArchived::ActiveRecord) ActiveRecord::Base.extend(ActsAsTokened::ActiveRecord) ActiveRecord::Base.extend(ActsAsSlugged::ActiveRecord) ActiveRecord::Base.extend(ActsAsStatused::ActiveRecord) ActiveRecord::Base.extend(EffectiveResource::ActiveRecord) end end initializer 'effective_resources.cancancan' do |app| if defined?(CanCan::Ability) CanCan::Ability.module_eval do CRUD_ACTIONS = [:index, :new, :create, :edit, :update, :show, :destroy] def crud CRUD_ACTIONS end end CanCan::Ability.include(ActsAsArchived::CanCan) CanCan::Ability.include(ActsAsStatused::CanCan) end end end end
lhursh/YLogging
YLogging.podspec
Pod::Spec.new do |s| s.name = "YLogging" s.version = "1.0.0" s.summary = "Short description of 'YLogging' framework" s.homepage = "http://www.listrak.com" s.license = "MIT" s.author = "<NAME>" s.platform = :ios, "10.0" s.source = {:git=>"https://github.com/lhursh/YLogging.git", :tag => "1.0.0"} s.source_files = "YLogging", "YLogging/**/*.{h,m,swift}" end
lhursh/YLogging
YLogging-Pod-Folder/YLogging.podspec
<filename>YLogging-Pod-Folder/YLogging.podspec<gh_stars>0 Pod::Spec.new do |s| s.name = "YLogging" s.version = "1.0.0" s.summary = "Short description of 'YLogging' framework" s.homepage = "http://www.listrak.com" s.license = "MIT" s.author = "<NAME>" s.platform = :ios, "10.0" s.source = {:http => 'https://github.com/lhursh/YLogging/blob/master/YLogging.zip'} s.ios.vendored_frameworks = 'YLogging.framework' end
ricardotk002/machina
lib/machina/dependencies.rb
<reponame>ricardotk002/machina<filename>lib/machina/dependencies.rb class Object def self.const_missing(c) require Machina.to_underscore(c.to_s) Object.const_get(c) end end
ricardotk002/machina
lib/machina.rb
require "machina/version" require "machina/routing" require "machina/util" require "machina/dependencies" require "machina/controller" require "machina/file_model" module Machina class Application def call(env) if env['PATH_INFO'] == '/favicon.ico' return [404, { 'Content-Type' => 'text/html' }, []] end klass, act = get_controller_and_action(env) controller = klass.new(env) text = controller.send(act) [200, { 'Content-Type' => 'text/html' }, [text]] end end end
ricardotk002/machina
lib/machina/controller.rb
require 'erubis' require 'machina/file_model' module Machina class Controller include Machina::Model attr_reader :env def initialize(env) @env = env end def render(view_name, locals = {}) filename = File.join("app", "views", controller_name, "#{view_name}.html.erb") template = File.read(filename) eruby = Erubis::Eruby.new(template) eruby.result(locals.merge(env: env)) end private def controller_name klass = self.class klass = klass.name.gsub(/Controller$/, "") Machina.to_underscore(klass) end end end
mlj/rss2pocket
lib/app.rb
<reponame>mlj/rss2pocket require_relative 'feed_db' require 'pocket-ruby' module PocketFetcher def self.run(&block) cache = Cache.new('config/feeds.yml') cache.each_url do |url| Feed.new(url, cache).fetch do |entry, tags| yield entry.url, tags end cache.save end end end config = YAML::load(File.open('config/config.yml')) pocket_client = ::Pocket.client access_token: config['access_token'], consumer_key: config['consumer_key'] while true PocketFetcher.run do |url, tags| pocket_client.add url: url, tags: tags end sleep 60 * 60 * 24 end
mlj/rss2pocket
lib/feed_db.rb
<filename>lib/feed_db.rb require 'feedjira' require 'httparty' require 'yaml' class Cache def initialize(cache_file = 'feeds.yml') if File.exists?(cache_file) @data = YAML::load_file(cache_file) @data = {} unless @data else @data = {} end @cache_file = cache_file end def save File.open(@cache_file, 'w') { |f| f.write @data.to_yaml } end def [](url) @data[url] ||= {} @data[url] end def each_url @data.keys.each do |url| yield url end end end class Feed def initialize(url, cache) @state = cache[url] @url = url @parser = Feedjira::Feed end MIN_YEAR = 1970 ONE_WEEK = 24 * 60 * 60 * 7 def update_last_fetched(timestamp) @state[:last_fetched] = timestamp unless timestamp.year < MIN_YEAR end def update_latest_url(url) @state[:latest_url] = url end def last_fetched @state[:last_fetched] # || Time.now - ONE_WEEK end def latest_url @state[:latest_url] end def tags @state[:tags] end def title @title end def fetch opts = {} opts['if-modified-since'] = last_fetched if last_fetched xml = HTTParty.get(@url, opts).body raw_feed= Feedjira.parse(xml) unless raw_feed.nil? or raw_feed == 304 or raw_feed == 0 or raw_feed == 500 or raw_feed == 200 or raw_feed == 404 stories = [] @title = raw_feed.title @feed_url = raw_feed.feed_url if raw_feed.last_modified && last_fetched && raw_feed.last_modified < last_fetched else raw_feed.entries.each do |story| break if latest_url && story.url == latest_url stories << story unless story.published && last_fetched && story.published < last_fetched end end stories.each do |story| yield story, tags end update_last_fetched(raw_feed.last_modified) update_latest_url(stories.first.url) unless stories.empty? end end end
lxl125z/LxlTest
LxlTest.podspec
Pod::Spec.new do |s| s.name = "LxlTest" s.version = "1.0.2" s.summary = "LxlTest is a test code by LXL." s.description = <<-DESC It is a marquee view used on iOS, which implement by Objective-C. DESC s.homepage = "https://github.com/lxl125z/LxlTest" s.license = 'MIT' s.author = { "lxl125z" => "<EMAIL>" } s.source = { :git => "https://github.com/lxl125z/LxlTest.git", :tag => s.version.to_s } s.platform = :ios, '8.0' # s.ios.deployment_target = '5.0' # s.osx.deployment_target = '10.7' s.requires_arc = true s.source_files = 'LxlTest/PodTest/*' # s.resources = 'Assets' # s.ios.exclude_files = 'Classes/osx' # s.osx.exclude_files = 'Classes/ios' # s.public_header_files = 'Classes/**/*.h' s.frameworks = 'Foundation', 'CoreGraphics', 'UIKit' end
vasinov/paper_trail
lib/paper_trail.rb
require "request_store" require "paper_trail/cleaner" require "paper_trail/config" require "paper_trail/has_paper_trail" require "paper_trail/record_history" require "paper_trail/reifier" require "paper_trail/version_association_concern" require "paper_trail/version_concern" require "paper_trail/version_number" require "paper_trail/serializers/json" require "paper_trail/serializers/yaml" # An ActiveRecord extension that tracks changes to your models, for auditing or # versioning. module PaperTrail extend PaperTrail::Cleaner class << self # @api private def clear_transaction_id self.transaction_id = nil end # Switches PaperTrail on or off. # @api public def enabled=(value) PaperTrail.config.enabled = value end # Returns `true` if PaperTrail is on, `false` otherwise. # PaperTrail is enabled by default. # @api public def enabled? !!PaperTrail.config.enabled end def serialized_attributes? ActiveSupport::Deprecation.warn( "PaperTrail.serialized_attributes? is deprecated without replacement " + "and always returns false." ) false end # Sets whether PaperTrail is enabled or disabled for the current request. # @api public def enabled_for_controller=(value) paper_trail_store[:request_enabled_for_controller] = value end # Returns `true` if PaperTrail is enabled for the request, `false` otherwise. # # See `PaperTrail::Rails::Controller#paper_trail_enabled_for_controller`. # @api public def enabled_for_controller? !!paper_trail_store[:request_enabled_for_controller] end # Sets whether PaperTrail is enabled or disabled for this model in the # current request. # @api public def enabled_for_model(model, value) paper_trail_store[:"enabled_for_#{model}"] = value end # Returns `true` if PaperTrail is enabled for this model in the current # request, `false` otherwise. # @api public def enabled_for_model?(model) !!paper_trail_store.fetch(:"enabled_for_#{model}", true) end # Set the field which records when a version was created. # @api public def timestamp_field=(field_name) PaperTrail.config.timestamp_field = field_name end # Returns the field which records when a version was created. # @api public def timestamp_field PaperTrail.config.timestamp_field end # Sets who is responsible for any changes that occur. You would normally use # this in a migration or on the console, when working with models directly. # In a controller it is set automatically to the `current_user`. # @api public def whodunnit=(value) paper_trail_store[:whodunnit] = value end # Returns who is reponsible for any changes that occur. # @api public def whodunnit paper_trail_store[:whodunnit] end # Sets any information from the controller that you want PaperTrail to # store. By default this is set automatically by a before filter. # @api public def controller_info=(value) paper_trail_store[:controller_info] = value end # Returns any information from the controller that you want # PaperTrail to store. # # See `PaperTrail::Rails::Controller#info_for_paper_trail`. # @api public def controller_info paper_trail_store[:controller_info] end # Getter and Setter for PaperTrail Serializer # @api public def serializer=(value) PaperTrail.config.serializer = value end # @api public def serializer PaperTrail.config.serializer end # Returns a boolean indicating whether "protected attibutes" should be # configured, e.g. attr_accessible, mass_assignment_sanitizer, # whitelist_attributes, etc. # @api public def active_record_protected_attributes? @active_record_protected_attributes ||= ::ActiveRecord::VERSION::MAJOR < 4 || !!defined?(ProtectedAttributes) end # @api public def transaction? ::ActiveRecord::Base.connection.open_transactions > 0 end # @api public def transaction_id paper_trail_store[:transaction_id] end # @api public def transaction_id=(id) paper_trail_store[:transaction_id] = id end # Thread-safe hash to hold PaperTrail's data. Initializing with needed # default values. # @api private def paper_trail_store RequestStore.store[:paper_trail] ||= { request_enabled_for_controller: true } end # Returns PaperTrail's configuration object. # @api private def config @config ||= PaperTrail::Config.instance yield @config if block_given? @config end alias configure config def version VERSION::STRING end end end # If available, ensure that the `protected_attributes` gem is loaded # before the `Version` class. unless PaperTrail.active_record_protected_attributes? PaperTrail.send(:remove_instance_variable, :@active_record_protected_attributes) begin require "protected_attributes" rescue LoadError # rubocop:disable Lint/HandleExceptions # In case `protected_attributes` gem is not available. end end ActiveSupport.on_load(:active_record) do include PaperTrail::Model end # Require frameworks require "paper_trail/frameworks/sinatra" if defined?(::Rails) && ActiveRecord::VERSION::STRING >= "3.2" require "paper_trail/frameworks/rails" else require "paper_trail/frameworks/active_record" end
vasinov/paper_trail
test/test_helper.rb
<reponame>vasinov/paper_trail<filename>test/test_helper.rb require "pry-nav" ENV["RAILS_ENV"] = "test" ENV["DB"] ||= "sqlite" unless File.exist?(File.expand_path("../../test/dummy/config/database.yml", __FILE__)) warn "WARNING: No database.yml detected for the dummy app, please run `rake prepare` first" end def using_mysql? @using_mysql ||= ActiveRecord::Base.connection_config[:adapter].to_sym == :mysql2 end require File.expand_path("../dummy/config/environment.rb", __FILE__) require "rails/test_help" require "shoulda" require "ffaker" require "database_cleaner" def active_record_gem_version Gem::Version.new(ActiveRecord::VERSION::STRING) end if active_record_gem_version >= Gem::Version.new("5.0.0.beta1") # See https://github.com/rails/rails-controller-testing/issues/5 ActionController::TestCase.send(:include, Rails::Controller::Testing::TestProcess) end Rails.backtrace_cleaner.remove_silencers! # Run any available migration ActiveRecord::Migrator.migrate File.expand_path("../dummy/db/migrate/", __FILE__) # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # DatabaseCleaner is apparently necessary for doing proper transactions within MySQL (ugh) DatabaseCleaner.strategy = :truncation # global setup block resetting Thread.current module ActiveSupport class TestCase if using_mysql? if respond_to? :use_transactional_tests= self.use_transactional_tests = false else self.use_transactional_fixtures = false end setup { DatabaseCleaner.start } end teardown do DatabaseCleaner.clean if using_mysql? Thread.current[:paper_trail] = nil end private def assert_attributes_equal(expected, actual) if using_mysql? expected = expected.dup actual = actual.dup # Adjust timestamps for missing fractional seconds precision. %w(created_at updated_at).each do |timestamp| expected[timestamp] = expected[timestamp].change(usec: 0) actual[timestamp] = actual[timestamp].change(usec: 0) end end assert_equal expected, actual end def assert_changes_equal(expected, actual) if using_mysql? expected = expected.dup actual = actual.dup # Adjust timestamps for missing fractional seconds precision. %w(created_at updated_at).each do |timestamp| expected[timestamp][1] = expected[timestamp][1].change(usec: 0) actual[timestamp][1] = actual[timestamp][1].change(usec: 0) end end assert_equal expected, actual end end end # # Helpers # def change_schema ActiveRecord::Migration.verbose = false ActiveRecord::Schema.define do remove_column :widgets, :sacrificial_column add_column :versions, :custom_created_at, :datetime end ActiveRecord::Migration.verbose = true reset_version_class_column_info! end # Wrap args in a hash to support the ActionController::TestCase and # ActionDispatch::Integration HTTP request method switch to keyword args # (see https://github.com/rails/rails/blob/master/actionpack/CHANGELOG.md) def params_wrapper(args) if defined?(::Rails) && active_record_gem_version >= Gem::Version.new("5.0.0.beta1") { params: args } else args end end def reset_version_class_column_info! PaperTrail::Version.connection.schema_cache.clear! PaperTrail::Version.reset_column_information end def restore_schema ActiveRecord::Migration.verbose = false ActiveRecord::Schema.define do add_column :widgets, :sacrificial_column, :string remove_column :versions, :custom_created_at end ActiveRecord::Migration.verbose = true reset_version_class_column_info! end
vasinov/paper_trail
spec/models/post_with_status_spec.rb
<reponame>vasinov/paper_trail require "rails_helper" # This model is in the test suite soley for the purpose of testing ActiveRecord::Enum, # which is available in ActiveRecord4+ only describe PostWithStatus, type: :model do if defined?(ActiveRecord::Enum) with_versioning do let(:post) { PostWithStatus.create!(status: "draft") } it "should stash the enum value properly in versions" do post.published! post.archived! expect(post.paper_trail.previous_version.published?).to be true end context "storing enum object_changes" do subject { post.versions.last } it "should stash the enum value properly in versions object_changes" do post.published! post.archived! expect(subject.changeset["status"]).to eql %w(published archived) end end end end end
vasinov/paper_trail
lib/paper_trail/attribute_serializers/cast_attribute_serializer.rb
<reponame>vasinov/paper_trail<gh_stars>0 module PaperTrail # :nodoc: module AttributeSerializers # The `CastAttributeSerializer` (de)serializes model attribute values. For # example, the string "1.99" serializes into the integer `1` when assigned # to an attribute of type `ActiveRecord::Type::Integer`. # # This implementation depends on the `type_for_attribute` method, which was # introduced in rails 4.2. In older versions of rails, we shim this method # with `LegacyActiveRecordShim`. if ::ActiveRecord::VERSION::MAJOR >= 5 # This implementation uses AR 5's `serialize` and `deserialize`. class CastAttributeSerializer def initialize(klass) @klass = klass end def serialize(attr, val) @klass.type_for_attribute(attr).serialize(val) end def deserialize(attr, val) @klass.type_for_attribute(attr).deserialize(val) end end else # This implementation uses AR 4.2's `type_cast_for_database`. For # versions of AR < 4.2 we provide an implementation of # `type_cast_for_database` in our shim attribute type classes, # `NoOpAttribute` and `SerializedAttribute`. class CastAttributeSerializer def initialize(klass) @klass = klass end def serialize(attr, val) val = defined_enums[attr][val] if defined_enums[attr] @klass.type_for_attribute(attr).type_cast_for_database(val) end def deserialize(attr, val) val = @klass.type_for_attribute(attr).type_cast_from_database(val) if defined_enums[attr] defined_enums[attr].key(val) else val end end private def defined_enums @defined_enums ||= (@klass.respond_to?(:defined_enums) ? @klass.defined_enums : {}) end end end end end
vasinov/paper_trail
test/paper_trail_test.rb
<gh_stars>0 require "test_helper" class PaperTrailTest < ActiveSupport::TestCase test "Sanity test" do assert_kind_of Module, PaperTrail::Version end test "Version Number" do assert PaperTrail.const_defined?(:VERSION) end context "setting enabled" do should "affect all threads" do Thread.new { PaperTrail.enabled = false }.join assert_equal false, PaperTrail.enabled? end teardown { PaperTrail.enabled = true } end test "create with plain model class" do widget = Widget.create assert_equal 1, widget.versions.length end test "update with plain model class" do widget = Widget.create assert_equal 1, widget.versions.length widget.update_attributes(name: "Bugle") assert_equal 2, widget.versions.length end test "destroy with plain model class" do widget = Widget.create assert_equal 1, widget.versions.length widget.destroy versions_for_widget = PaperTrail::Version.with_item_keys("Widget", widget.id) assert_equal 2, versions_for_widget.length end end
nsingh/apm-agent-ruby
lib/elastic_apm/transport/connection.rb
<filename>lib/elastic_apm/transport/connection.rb<gh_stars>0 # Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # frozen_string_literal: true module ElasticAPM module Transport # @api private class Connection include Logging # A connection holds an instance `http` of an Http::Connection. # # The HTTP::Connection itself is not thread safe. # # The connection sends write requests and close requests to `http`, and # has to ensure no write requests are sent after closing `http`. # # The connection schedules a separate thread to close an `http` # connection some time in the future. To avoid the thread interfering # with ongoing write requests to `http`, write and close # requests have to be synchronized. def initialize(config) @config = config @metadata = JSON.fast_generate( Serializers::MetadataSerializer.new(config).build( Metadata.new(config) ) ) @url = "#{config.server_url}/intake/v2/events" @mutex = Mutex.new end attr_reader :http def write(str) return false if @config.disable_send begin bytes_written = 0 # The request might get closed from timertask so let's make sure we # hold it open until we've written. @mutex.synchronize do connect if http.nil? || http.closed? bytes_written = http.write(str) end flush(:api_request_size) if bytes_written >= @config.api_request_size rescue IOError => e error('Connection error: %s', e.inspect) flush(:ioerror) rescue Errno::EPIPE => e error('Connection error: %s', e.inspect) flush(:broken_pipe) rescue Exception => e error('Connection error: %s', e.inspect) flush(:connection_error) end end def flush(reason = :force) # Could happen from the timertask so we need to sync @mutex.synchronize do return if http.nil? http.close(reason) end end def inspect format( '<%s url:%s closed:%s >', super.split.first, @url, http&.closed? ) end private def connect schedule_closing if @config.api_request_time @http = Http.open(@config, @url).tap do |http| http.write(@metadata) end end # rubocop:enable def schedule_closing @close_task&.cancel @close_task = Concurrent::ScheduledTask.execute(@config.api_request_time) do flush(:timeout) end end end end end
nsingh/apm-agent-ruby
spec/elastic_apm/sql_summarizer_spec.rb
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # frozen_string_literal: true require 'spec_helper' require 'elastic_apm/sql_summarizer' module ElasticAPM RSpec.describe SqlSummarizer do it 'summarizes selects from table' do result = subject.summarize('SELECT * FROM "table"') expect(result).to eq('SELECT FROM table') end it 'summarizes selects from table with columns' do result = subject.summarize('SELECT a, b FROM table') expect(result).to eq('SELECT FROM table') end it 'summarizes selects from table with underscore' do result = subject.summarize('SELECT * FROM my_table') expect(result).to eq('SELECT FROM my_table') end it 'simplifies advanced selects' do result = subject.summarize("select months.month, count(created_at) from (select DATE '2017-06-09'+(interval '1' month * generate_series(0,11)) as month, DATE '2017-06-10'+(interval '1' month * generate_series(0,11)) as next) months left outer join subscriptions on created_at < month and (soft_destroyed_at IS NULL or soft_destroyed_at >= next) and (suspended_at IS NULL OR suspended_at >= next) group by month order by month desc") # rubocop:disable Layout/LineLength expect(result).to eq('SQL') end it 'summarizes inserts' do sql = "INSERT INTO table (a, b) VALUES ('A','B')" result = subject.summarize(sql) expect(result).to eq('INSERT INTO table') end it 'summarizes updates' do sql = "UPDATE table SET a = 'B' WHERE b = 'B'" result = subject.summarize(sql) expect(result).to eq('UPDATE table') end it 'summarizes deletes' do result = subject.summarize("DELETE FROM table WHERE b = 'B'") expect(result).to eq('DELETE FROM table') end it 'sumarizes transactions' do result = subject.summarize('BEGIN') expect(result).to eq('BEGIN') result = subject.summarize('COMMIT') expect(result).to eq('COMMIT') end it 'is default when unknown' do sql = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS varchar)" result = subject.summarize(sql) expect(result).to eq 'SQL' end context 'invalid bytes' do it 'replaces invalid bytes' do sql = "INSERT INTO table (a, b) VALUES ('\255','\255')" result = subject.summarize(sql) expect(result).to eq('INSERT INTO table') end end end end
nsingh/apm-agent-ruby
lib/elastic_apm/metadata/service_info.rb
<reponame>nsingh/apm-agent-ruby # Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # frozen_string_literal: true module ElasticAPM class Metadata # @api private class ServiceInfo # @api private class Versioned def initialize(name: nil, version: nil) @name = name @version = version end attr_reader :name, :version end class Agent < Versioned; end class Framework < Versioned; end class Language < Versioned; end class Runtime < Versioned; end def initialize(config) @config = config @name = @config.service_name @node_name = @config.service_node_name @environment = @config.environment @agent = Agent.new(name: 'ruby', version: VERSION) @framework = Framework.new( name: @config.framework_name, version: @config.framework_version ) @language = Language.new(name: 'ruby', version: RUBY_VERSION) @runtime = lookup_runtime @version = @config.service_version || Util.git_sha end attr_reader :name, :node_name, :environment, :agent, :framework, :language, :runtime, :version private def lookup_runtime case RUBY_ENGINE when 'ruby' Runtime.new( name: RUBY_ENGINE, version: RUBY_VERSION || RUBY_ENGINE_VERSION ) when 'jruby' Runtime.new( name: RUBY_ENGINE, version: JRUBY_VERSION || RUBY_ENGINE_VERSION ) end end end end end
nsingh/apm-agent-ruby
spec/elastic_apm/spies/mongo_spec.rb
<filename>spec/elastic_apm/spies/mongo_spec.rb # Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # frozen_string_literal: true require 'spec_helper' require 'mongo' module ElasticAPM RSpec.describe 'Spy: MongoDB' do context 'db admin commands' do let(:event) do double('event', command: { 'listCollections' => 1 }, command_name: 'listCollections', database_name: 'elastic-apm-test', operation_id: 123) end let(:subscriber) { Spies::MongoSpy::Subscriber.new } it 'captures command properties', :intercept do span = with_agent do ElasticAPM.with_transaction do subscriber.started(event) subscriber.succeeded(event) end end expect(span.name).to eq 'elastic-apm-test.listCollections' expect(span.type).to eq 'db' expect(span.subtype).to eq 'mongodb' expect(span.action).to eq 'query' expect(span.duration).to_not be_nil expect(span.outcome).to eq 'success' db = span.context.db expect(db.instance).to eq 'elastic-apm-test' expect(db.type).to eq 'mongodb' expect(db.statement).to eq('{"listCollections"=>1}') expect(db.user).to be nil destination = span.context.destination expect(destination.name).to eq 'mongodb' expect(destination.resource).to eq 'mongodb' expect(destination.type).to eq 'db' end it 'sets outcome to `failure` for a failed operation', :intercept do span = with_agent do ElasticAPM.with_transaction do subscriber.started(event) subscriber.failed(event) end end expect(span.outcome).to eq 'failure' end end context 'collection commands', :intercept do let(:event) do double('event', command: { 'find' => 'testing', 'filter' => { 'a' => 'bc' } }, command_name: 'find', database_name: 'elastic-apm-test', operation_id: 456) end let(:subscriber) { Spies::MongoSpy::Subscriber.new } it 'captures command properties' do span = with_agent do ElasticAPM.with_transaction do subscriber.started(event) subscriber.succeeded(event) end end expect(span.name).to eq 'elastic-apm-test.testing.find' expect(span.type).to eq 'db' expect(span.subtype).to eq 'mongodb' expect(span.action).to eq 'query' expect(span.duration).to_not be_nil expect(span.outcome).to eq 'success' db = span.context.db expect(db.instance).to eq 'elastic-apm-test' expect(db.type).to eq 'mongodb' expect(db.statement).to eq('{"find"=>"testing", "filter"=>{"a"=>"bc"}}') expect(db.user).to be nil end end end end