Skip to content
Browse files

Renamed truefalse method to_boolean and moved into ActiveRDF::Helpers

Moved benchmark method into ActiveRDF::Helpers
Minor reformatting
  • Loading branch information...
1 parent dddafc9 commit efdd52ad5cee7980ae232a3fd61d3b5f9da957fa @michaeldiamond michaeldiamond committed
View
7 activerdf-rdflite/lib/activerdf_rdflite/rdflite.rb
@@ -15,6 +15,7 @@
module ActiveRDF
class RDFLite < ActiveRdfAdapter
ActiveRdfLogger::log_info(self) { "Loading RDFLite adapter" }
+ include Helpers
begin
require 'ferret'
@@ -36,7 +37,7 @@ def initialize(params = {})
super
ActiveRdfLogger::log_info(self) { "Initialised rdflite with params #{params.to_s}" }
- @reasoning = truefalse(params[:reasoning], false)
+ @reasoning = to_boolean(params[:reasoning], false)
@subprops = {} if @reasoning
# if no file-location given, we use in-memory store
@@ -44,13 +45,13 @@ def initialize(params = {})
@db = SQLite3::Database.new(file)
# disable keyword search by default, enable only if ferret is found
- @keyword_search = truefalse(params[:keyword], false) && @@have_ferret
+ @keyword_search = to_boolean(params[:keyword], false) && @@have_ferret
# turn off filesystem synchronisation for speed
@db.synchronous = 'off'
# drop the table if a new datastore is requested
- @db.execute('drop table if exists triple') if truefalse(params[:new],false)
+ @db.execute('drop table if exists triple') if to_boolean(params[:new],false)
# create triples table. ignores duplicated triples
@db.execute('create table if not exists triple(s,p,o,c, unique(s,p,o,c) on conflict ignore)')
View
4 activerdf-redland/lib/activerdf_redland/redland.rb
@@ -10,6 +10,8 @@
# uses SPARQL for querying
module ActiveRDF
class RedlandAdapter < ActiveRdfAdapter
+ include Helpers
+
ActiveRdfLogger::log_info "Loading Redland adapter", self
ConnectionPool.register_adapter(:redland,self)
@@ -43,7 +45,7 @@ def initialize(params = {})
[:host, :port, :database, :user, :password].each{|k| options[k] = params[k] if params[k]}
options[:host] ||= 'localhost'
end
- options[:reconnect] = truefalse(params[:reconnect], false) if location == 'mysql'
+ options[:reconnect] = to_boolean(params[:reconnect], false) if location == 'mysql'
when 'memory',nil
# use storage module hashes with hash-type 'memory' instead of non-indexing storage module memory
store_type = 'hashes'
View
4 activerdf-sparql/lib/activerdf_sparql/sparql.rb
@@ -7,6 +7,8 @@
module ActiveRDF
# SPARQL adapter
class SparqlAdapter < ActiveRdfAdapter
+ include Helpers
+
ActiveRdfLogger::log_info(self) { "Loading SPARQL adapter" }
ConnectionPool.register_adapter(:sparql, self)
@@ -172,7 +174,7 @@ def parse_json(response_str, resource_type)
response = JSON.parse(response_str)
return [] if response.nil?
- return [truefalse(response['boolean'])] if response.has_key?('boolean')
+ return [to_boolean(response['boolean'])] if response.has_key?('boolean')
results = []
vars = response['head']['vars']
View
2 activerdf-sparql/lib/activerdf_sparql/sparql_result_parser.rb
@@ -36,7 +36,7 @@ def tag_end(name)
def text(text)
if !@current_type.nil?
if @current_type == 'boolean'
- @result = [truefalse(text)]
+ @result = [to_boolean(text)]
else
@current_result[@index] = create_node(@current_type, text)
end
View
70 lib/active_rdf/helpers.rb
@@ -2,6 +2,39 @@
# Default ActiveRDF error
module ActiveRDF
class ActiveRdfError < StandardError; end
+
+ # extract boolean from value
+ module Helpers
+ def to_boolean(val, default = nil)
+ raise ArgumentError, "to_boolean: default must be a boolean: #{default}" if !default.nil? and !(default == true || default == false)
+ case val
+ when true,/^(y|yes|t|true|)$/i then true
+ when false,/^(n|no|f|false)$/i then false
+ else default
+ end
+ end
+
+ # Benchmarking for ActiveRecord. You may pass a message with additional
+ # information - there's a little hack that the "real" benchmark will pass
+ # the message to the block, while the "non-benchmark" call will pass nil.
+ # This allows you to build the message in the block only if you need it.
+ def benchmark(title, log_level = Logger::DEBUG, message = '')
+ if(ActiveRdfLogger.logger.level <= log_level)
+ result = nil
+ seconds = ::Benchmark.realtime { result = yield(message) }
+ ActiveRdfLogger.log_add("\033[31m\033[1m#{title}\033[0m (#{'%.5f' % seconds}) -- \033[34m#{message}\033[0m", log_level, self)
+ result
+ else
+ yield(nil)
+ end
+ end
+ end
+end
+
+class Array
+ def extract_options!
+ last.is_a?(::Hash) ? pop : {}
+ end
end
class Module
@@ -24,39 +57,4 @@ def #{sym}?
EOS
end
end
-end
-
-class Array
- def extract_options!
- last.is_a?(::Hash) ? pop : {}
- end
-end
-
-# extract boolean from value
-def truefalse(val, default = nil)
- raise ArgumentError, "truefalse: default must be a boolean: #{default}" if !default.nil? and !(default == true || default == false)
- case val
- when true,/^(yes|y|true)$/i then true
- when false,/^(no|n|false)$/i then false
- else default
- end
-end
-
-
-module ActiveRdfBenchmark
- # Benchmarking for ActiveRecord. You may pass a message with additional
- # information - there's a little hack that the "real" benchmark will pass
- # the message to the block, while the "non-benchmark" call will pass nil.
- # This allows you to build the message in the block only if you need it.
- def benchmark(title, log_level = Logger::DEBUG, message = '')
- if(ActiveRdfLogger.logger.level <= log_level)
- result = nil
- seconds = Benchmark.realtime { result = yield(message) }
- ActiveRdfLogger.log_add("\033[31m\033[1m#{title}\033[0m (#{'%.5f' % seconds}) -- \033[34m#{message}\033[0m", log_level, self)
- result
- else
- yield(nil)
- end
- end
-
-end
+end
View
4 lib/active_rdf/model/property.rb
@@ -63,7 +63,9 @@ def property
# Provides methods for accessing property values when @subject is set
module AssociatedProperty
+ include ActiveRDF::Helpers
include Enumerable
+
# Value reference. Retrieves a copy of the value by the key or value. Returns nil if not found.
def [](md5_or_value)
unless md5_or_value.nil?
@@ -281,7 +283,7 @@ def lang(tag = nil, exact = true)
def lang=(*args)
args.flatten!
@lang = args[0].sub(/^@/,'')
- @exact_lang = truefalse(args[1],true)
+ @exact_lang = to_boolean(args[1],true)
end
# Returns the number of values assigned to this property for this @subject
View
3 lib/active_rdf/model/resource_query.rb
@@ -15,6 +15,7 @@ module ActiveRDF
# ResourceQuery.new(RDFS::Resource).test::age(27).execute # find RDFS::Resources having the fully qualified property and value
# ResourceQuery.new(TEST::Person).age(27).eye(LocalizedString('blue','en')).execute # chain multiple properties together, ANDing restrictions
class ResourceQuery
+ include Helpers
private(:type)
def initialize(type,context = nil)
@@ -25,7 +26,7 @@ def initialize(type,context = nil)
end
def execute(options = {}, &blk)
- if truefalse(options[:all_types])
+ if to_boolean(options[:all_types])
if @query.filter_clauses.values.any?{|operator,operand| operator == :lang or operator == :datatype}
raise ActiveRdfError, "all_types may not be specified in conjunction with any lang or datatype restrictions"
end
View
4 lib/active_rdf/query/query.rb
@@ -6,6 +6,8 @@
# Query.new.select(:s).where(:s,:p,:o).
module ActiveRDF
class Query
+ include Helpers
+
attr_reader :select_clauses, :where_clauses, :filter_clauses, :sort_clauses, :limits, :offsets, :keywords
bool_accessor :distinct, :ask, :select, :count, :keyword, :all_types
@@ -81,7 +83,7 @@ def ask
# Request reasoning be performed on query
def reasoning(bool)
- @reasoning = truefalse(bool)
+ @reasoning = to_boolean(bool)
self
end
def reasoning=(bool)
View
123 lib/active_rdf/storage/federated_store.rb
@@ -1,13 +1,16 @@
require 'active_rdf/storage/connection_pool'
-include ActiveRdfBenchmark
-
# Manages the federation of datasources: distributes queries to right
# datasources and merges their results
module ActiveRDF
+
class FederationManager
- def FederationManager.contexts
+ class << self
+ include Helpers
+ end
+
+ def FederationManager.contexts
ConnectionPool.adapters.collect{|adapter| adapter.contexts if adapter.respond_to?(:contexts)}.flatten.compact
end
@@ -15,21 +18,21 @@ def FederationManager.contexts
def FederationManager.add(s,p,o,c=nil)
benchmark("SPARQL/RDF", Logger::DEBUG) do |bench_message|
bench_message << "ADD #{s} - #{p} - #{o} : #{c}" if(bench_message)
- # TODO: allow addition of full graphs
- raise ActiveRdfError, "cannot write without a write-adapter" unless ConnectionPool.write_adapter
+ # TODO: allow addition of full graphs
+ raise ActiveRdfError, "cannot write without a write-adapter" unless ConnectionPool.write_adapter
ConnectionPool.write_adapter.add(s,p,o,c)
- end
+ end
end
# delete triple s,p,o (context is optional) to the currently selected write-adapter
def FederationManager.delete(s,p=nil,o=nil,c=nil)
benchmark("SPARQL/RDF", Logger::DEBUG) do |bench_message|
bench_message << "DELETE #{s} - #{p} - #{o} : #{c}" if(bench_message)
- raise ActiveRdfError, "cannot write without a write-adapter" unless ConnectionPool.write_adapter
- # transform wildcard symbols to nil (for the adaptors)
- s = nil if s.is_a? Symbol
- p = nil if p.is_a? Symbol
- o = nil if o.is_a? Symbol
+ raise ActiveRdfError, "cannot write without a write-adapter" unless ConnectionPool.write_adapter
+ # transform wildcard symbols to nil (for the adaptors)
+ s = nil if s.is_a? Symbol
+ p = nil if p.is_a? Symbol
+ o = nil if o.is_a? Symbol
ConnectionPool.write_adapter.delete(s,p,o,c)
end
end
@@ -57,60 +60,60 @@ def FederationManager.execute(q, options={:flatten => false})
benchmark("SPARQL/RDF", Logger::DEBUG) do |bench_message|
# Only build the benchmark message if we need it
bench_message << ((q.class == String) ? q : q.to_sp) if(bench_message)
- # ask each adapter for query results
- # and yield them consequtively
- if block_given?
- ConnectionPool.read_adapters.each do |source|
- source.execute(q) do |*clauses|
- yield(*clauses)
+ # ask each adapter for query results
+ # and yield them consequtively
+ if block_given?
+ ConnectionPool.read_adapters.each do |source|
+ source.execute(q) do |*clauses|
+ yield(*clauses)
+ end
end
- end
- else
- # build Array of results from all sources
- # TODO: write test for sebastian's select problem
- # (without distinct, should get duplicates, they
- # were filtered out when doing results.union)
- results = []
- ConnectionPool.read_adapters.each do |source|
- source_results = source.execute(q)
- source_results.each do |clauses|
- results << clauses
+ else
+ # build Array of results from all sources
+ # TODO: write test for sebastian's select problem
+ # (without distinct, should get duplicates, they
+ # were filtered out when doing results.union)
+ results = []
+ ConnectionPool.read_adapters.each do |source|
+ source_results = source.execute(q)
+ source_results.each do |clauses|
+ results << clauses
+ end
end
- end
- # ask queries return boolean values. the results array will contain one for each adapter: [false,true,...]
- # if any adapter returned true, then return true
- return results.any?{|val| val.is_a?(TrueClass)} if q.ask?
-
- # count
- return results.flatten.inject{|mem,c| mem + c} if q.count?
-
- # filter the empty results
- results.reject {|ary| ary.empty? }
-
- # remove duplicate results from multiple
- # adapters if asked for distinct query
- # (adapters return only distinct results,
- # but they cannot check duplicates against each other)
- results.uniq! if q.distinct?
-
- # flatten results array if only one select clause
- # to prevent unnecessarily nested array [[eyal],[renaud],...]
- results.flatten! if q.select_clauses.size == 1 or q.ask?
-
- # remove array (return single value or nil) if asked to
- if options[:flatten]
- case results.size
- when 0
- results = nil
- when 1
- results = results.first
+ # ask queries return boolean values. the results array will contain one for each adapter: [false,true,...]
+ # if any adapter returned true, then return true
+ return results.any?{|val| val.is_a?(TrueClass)} if q.ask?
+
+ # count
+ return results.flatten.inject{|mem,c| mem + c} if q.count?
+
+ # filter the empty results
+ results.reject {|ary| ary.empty? }
+
+ # remove duplicate results from multiple
+ # adapters if asked for distinct query
+ # (adapters return only distinct results,
+ # but they cannot check duplicates against each other)
+ results.uniq! if q.distinct?
+
+ # flatten results array if only one select clause
+ # to prevent unnecessarily nested array [[eyal],[renaud],...]
+ results.flatten! if q.select_clauses.size == 1 or q.ask?
+
+ # remove array (return single value or nil) if asked to
+ if options[:flatten]
+ case results.size
+ when 0
+ results = nil
+ when 1
+ results = results.first
+ end
end
end
- end
- results
+ results
end # End benchmark
- end # End query
- end
+ end # End execute
end
+end
View
8 lib/active_rdf/storage/store.rb
@@ -3,6 +3,8 @@
# Generic superclass of all adapters
module ActiveRDF
class ActiveRdfAdapter
+ include Helpers
+
# indicate if adapter can read and write
bool_accessor :enabled, :reads, :writes, :new, :contexts, :enabled
@@ -14,9 +16,9 @@ def initialize(params = {})
# defaults
@enabled = true
@reads = true
- @writes = truefalse(params[:write], true)
- @new = truefalse(params[:new], false)
- @contexts = truefalse(params[:contexts], false)
+ @writes = to_boolean(params[:write], true)
+ @new = to_boolean(params[:new], false)
+ @contexts = to_boolean(params[:contexts], false)
end
# translate a query to its string representation

0 comments on commit efdd52a

Please sign in to comment.
Something went wrong with that request. Please try again.