repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/message_content/tool_result.rb
lib/intelligence/message_content/tool_result.rb
module Intelligence module MessageContent class ToolResult < Base schema do tool_call_id tool_name String, required: true tool_result [ Hash, String ] end attribute :tool_call_id, :tool_name, :tool_result def valid? tool_call_id && !tool_call_id.empty? && tool_name && !tool_name.empty? end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/message_content/base.rb
lib/intelligence/message_content/base.rb
module Intelligence module MessageContent class Base include DynamicSchema::Definable class << self def attribute( *names ) names.each do | name | define_method( name ) { @attributes[ name ] } end end def type @type ||= begin _type = name.split( '::' ).last.dup _type.gsub!( /([A-Z]+)([A-Z][a-z])/, '\1_\2' ) _type.gsub!( /([a-z\d])([A-Z])/, '\1_\2' ) _type.tr!( '-', '_' ) _type.downcase! _type.to_sym end end def build( attributes = nil, &block ) new( ( attributes || {} ).merge( builder.build( attributes, &block ) ) ) end def build!( attributes = nil, &block ) new( ( attributes || {} ).merge( builder.build!( attributes, &block ) ) ) end end def initialize( attributes = nil ) @attributes = {} attributes = attributes.except( :type ) if attributes attributes&.each { | key, value | @attributes[ key.to_sym ] = value.freeze } end def valid? false end def []( key ) @attributes[ key.to_sym ] end def type self.class.type end def to_h { type: type }.merge( @attributes ).compact end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/message_content/web_search_call.rb
lib/intelligence/message_content/web_search_call.rb
module Intelligence module MessageContent class WebSearchCall < Base schema do status Symbol, in: [ :searching, :complete ] query String end attribute :status, :query def valid? true end def complete? @status.to_s == 'complete' end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/message_content/tool_call.rb
lib/intelligence/message_content/tool_call.rb
module Intelligence module MessageContent class ToolCall < Base schema do tool_call_id String tool_name String, required: true tool_parameters [ Hash, String ] end attribute :tool_call_id, :tool_name def tool_parameters( options = nil ) raw = @attributes[ :tool_parameters ] return raw \ if raw.nil? || raw.is_a?( Hash ) || ( raw.is_a?( String ) && raw.empty? ) options = options || {} parse = options.key?( :parse ) ? options[ :parse ] : true return @parsed_tool_parameters if @parsed_tool_parameters && parse tool_parameters = begin if ( parse && ( options.key?( :repair ) ? options[ :repair ] : true ) ) JSON.repair( raw ) else raw end rescue JSON::JSONRepairError raw end if parse begin @parsed_tool_parameters = tool_parameters = JSON.parse( tool_parameters, parse.is_a?( Hash ) ? parse : { symbolize_names: true } ) rescue JSON::ParserError end end tool_parameters end def valid? tool_name && !tool_name.empty? end def to_h super.merge( tool_parameters: tool_parameters ) end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/message_content/cipher_thought.rb
lib/intelligence/message_content/cipher_thought.rb
module Intelligence module MessageContent class CipherThought < Base # note: a cipher thought has no portable payload; only vendor specific # payloads; such as that from openai def valid? true end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/generic.rb
lib/intelligence/adapters/generic.rb
require_relative '../adapter' require_relative 'generic/adapter'
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/hyperbolic.rb
lib/intelligence/adapters/hyperbolic.rb
require_relative 'generic/adapter' module Intelligence module Hyperbolic class Adapter < Generic::Adapter DEFAULT_BASE_URI = 'https://api.hyperbolic.xyz/v1' schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do model String temperature Float top_p Float n Integer max_tokens Integer stop String, array: true stream [ TrueClass, FalseClass ] frequency_penalty Float presence_penalty Float user String end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/x_ai.rb
lib/intelligence/adapters/x_ai.rb
require_relative 'generic/adapter' require_relative 'x_ai/adapter'
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/cerebras.rb
lib/intelligence/adapters/cerebras.rb
require_relative 'generic/adapter' module Intelligence module Cerebras class Adapter < Generic::Adapter DEFAULT_BASE_URI = 'https://api.cerebras.ai/v1' schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do model String max_tokens Integer response_format do type String, default: 'json_schema' json_schema end seed Integer stop array: true stream [ TrueClass, FalseClass ] temperature Float top_p Float tool array: true, as: :tools, &Tool.schema tool_choice do type String mame String end user String end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/ollama.rb
lib/intelligence/adapters/ollama.rb
require_relative 'generic/adapter' module Intelligence module Ollama class Adapter < Generic::Adapter DEFAULT_BASE_URI = 'http://localhost:11435/v1' schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do max_tokens Integer model String stop String, array: true stream [ TrueClass, FalseClass ] temperature Float end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/mistral.rb
lib/intelligence/adapters/mistral.rb
require_relative 'generic/adapter' module Intelligence module Mistral class Adapter < Generic::Adapter DEFAULT_BASE_URI = "https://api.mistral.ai/v1" schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do model String temperature Float top_p Float max_tokens Integer min_tokens Integer seed Integer, as: :random_seed stop String, array: true stream [ TrueClass, FalseClass ] random_seed Integer response_format do type String end tool array: true, as: :tools, &Tool.schema tool_choice do type String function do name String end end end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/samba_nova.rb
lib/intelligence/adapters/samba_nova.rb
require_relative 'generic/adapter' module Intelligence module SambaNova class Adapter < Generic::Adapter DEFAULT_BASE_URI = "https://api.sambanova.ai/v1" schema do # normalized properties for all endpoints base_uri String, default: DEFAULT_BASE_URI key String # properties for generative text endpoints chat_options do # normalized properties for samba nova generative text endpoint model String max_tokens Integer temperature Float top_p Float top_k Float stop String, array: true stream [ TrueClass, FalseClass ] # samba nova properties for samba nova generative text endpoint repetition_penalty Float stream_options do include_usage [ TrueClass, FalseClass ] end end end def chat_result_error_attributes( response ) error_type, error_description = to_error_response( response.status ) result = { error_type: error_type.to_s, error_description: error_description } parsed_body = JSON.parse( response.body, symbolize_names: true ) rescue nil if parsed_body && parsed_body.respond_to?( :include? ) && parsed_body.include?( :error ) && parsed_body[ :error ].is_a?( String ) result[ :error_description ] = parsed_body[ :error ] elsif response.headers[ 'content-type' ].start_with?( 'text/plain' ) && response.body && response.body.length > 0 result[ :error_description ] = response.body end result end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/google.rb
lib/intelligence/adapters/google.rb
require_relative '../adapter' require_relative 'google/adapter'
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/anthropic.rb
lib/intelligence/adapters/anthropic.rb
require_relative '../adapter' require_relative 'anthropic/adapter' require_relative 'anthropic/extensions'
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/azure.rb
lib/intelligence/adapters/azure.rb
require_relative 'generic' module Intelligence module Azure class Adapter < Generic::Adapter CHAT_COMPLETIONS_PATH = 'chat/completions' schema do # normalized properties, used by all endpoints base_uri String, required: true key String api_version String, required: true, default: '2025-01-01-preview' # properties for generative text endpoints chat_options do # normalized properties for openai generative text endpoint model String, requried: true max_tokens Integer, in: (0...) temperature Float, in: (0..1) top_p Float, in: (0..1) seed Integer stop String, array: true stream [ TrueClass, FalseClass ] frequency_penalty Float, in: (-2..2) presence_penalty Float, in: (-2..2) modalities String, array: true response_format do # 'text' and 'json_schema' are the only supported types type Symbol, in: [ :text, :json_schema ] json_schema end # tools tool array: true, as: :tools, &Tool.schema # tool choice configuration # # `tool_choice :none` # or # ``` # tool_choice :function do # function :my_function # end # ``` tool_choice arguments: :type do type Symbol, in: [ :none, :auto, :required ] function arguments: :name do name Symbol end end # the parallel_tool_calls parameter is only allowed when 'tools' are specified parallel_tool_calls [ TrueClass, FalseClass ] end end def chat_request_uri( options = nil ) options = merge_options( @options, build_options( options ) ) base_uri = options[ :base_uri ] if base_uri # because URI join is dumb base_uri = ( base_uri.end_with?( '/' ) ? base_uri : base_uri + '/' ) uri = URI.join( base_uri, CHAT_COMPLETIONS_PATH ) api_version = options[ :api_version ] || options[ 'api-version' ] uri.query = [ uri.query, "api-version=#{ api_version }" ].compact.join( '&' ) uri else raise 'The Azure adapter requires a base_uri.' end end def chat_request_headers( options = {} ) options = merge_options( @options, build_options( options ) ) result = {} key = options[ :key ] raise ArgumentError.new( "An Azure key is required to build an Azure request." ) \ if key.nil? result[ 'Content-Type' ] = 'application/json' result[ 'api-key' ] = key result end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/together_ai.rb
lib/intelligence/adapters/together_ai.rb
require_relative 'generic/adapter' module Intelligence module TogetherAi class Adapter < Generic::Adapter DEFAULT_BASE_URI = "https://api.together.xyz/v1" schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do model String temperature Float top_p Float top_k Integer n Integer max_tokens Float stop String, array: true stream [ TrueClass, FalseClass ] frequency_penalty Float presence_penalty Float repetition_penalty Float # together ai tools tool array: true, as: :tools, &Tool.schema # together ai tool choice configuration # # `tool_choice :auto` # or # ``` # tool_choice :function do # function :my_function # end # ``` tool_choice arguments: :type do type Symbol, in: [ :none, :auto, :function ] function arguments: :name do name Symbol end end user String end end def to_end_reason( end_result ) case end_result when 'eos', 'stop' :ended # unfortunatelly eos seems to only work with certain models while others always return # stop so for now tomorrow ai will not support :end_sequence_encountered # when 'stop' # :end_sequence_encountered when 'length' :token_limit_exceeded when 'tool_calls' :tool_called else nil end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/parallax.rb
lib/intelligence/adapters/parallax.rb
require_relative 'generic/adapter' module Intelligence module Parallax class Adapter < Generic::Adapter DEFAULT_BASE_URI = 'http://localhost:3000/v1' schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do max_tokens Integer model String stop String, array: true stream [ TrueClass, FalseClass ] temperature Float template_arguments as: :chat_template_kwargs do enable_thinking [ TrueClass, FalseClass ] end end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/open_router.rb
lib/intelligence/adapters/open_router.rb
require_relative 'generic/adapter' module Intelligence module OpenRouter class Adapter < Generic::Adapter DEFAULT_BASE_URI = 'https://openrouter.ai/api/v1' schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do model String temperature Float top_k Integer top_p Float max_tokens Integer seed Integer stop String, array: true stream [ TrueClass, FalseClass ] frequency_penalty Float repetition_penalty Float presence_penalty Float provider do order String, array: true require_parameters [ TrueClass, FalseClass ] allow_fallbacks [ TrueClass, FalseClass ] end end end # def chat_result_error_attributes( response ) # # error_type, error_description = translate_error_response_status( response.status ) # result = { # error_type: error_type.to_s, # error_description: error_description # } # parsed_body = JSON.parse( response.body, symbolize_names: true ) rescue nil # if parsed_body && parsed_body.respond_to?( :include? ) # if parsed_body.include?( :error ) # result = { # error_type: error_type.to_s, # error: parsed_body[ :error ][ :code ] || error_type.to_s, # error_description: parsed_body[ :error ][ :message ] || error_description # } # elsif parsed_body.include?( :detail ) # result[ :error_description ] = parsed_body[ :detail ] # elsif parsed_body[ :object ] == 'error' # result[ :error_description ] = parsed_body[ :message ] # end # end # # result # # end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/groq.rb
lib/intelligence/adapters/groq.rb
require_relative 'generic/adapter' module Intelligence module Groq class Adapter < Generic::Adapter DEFAULT_BASE_URI = 'https://api.groq.com/openai/v1' schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do frequency_penalty Float logit_bias logprobs [ TrueClass, FalseClass ] max_tokens Integer model String # the parallel_tool_calls is only allowed when 'tools' are specified parallel_tool_calls [ TrueClass, FalseClass ] presence_penalty Float response_format do # 'text' and 'json_object' are the only supported types; you must also instruct # the model to output json type Symbol, in: [ :text, :json_object ] end seed Integer stop String, array: true stream [ TrueClass, FalseClass ] stream_options do include_usage [ TrueClass, FalseClass ] end temperature Float tool array: true, as: :tools, &Tool.schema tool_choice do # one of 'auto', 'none' or 'function' type Symbol, in: [ :auto, :none, :function ] # the function parameters is required if you specify a type of 'function' function do name String end end top_logprobs Integer top_p Float user String end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/open_ai_legacy.rb
lib/intelligence/adapters/open_ai_legacy.rb
require_relative 'generic/adapter' module Intelligence module OpenAiLegacy class Adapter < Generic::Adapter DEFAULT_BASE_URI = 'https://api.openai.com/v1' schema do # normalized properties, used by all endpoints base_uri String, default: DEFAULT_BASE_URI key String # openai properties, used by all endpoints organization String project String # properties for generative text endpoints chat_options do # normalized properties for openai generative text endpoint model String, requried: true n Integer max_tokens Integer, as: :max_completion_tokens temperature Float top_p Float seed Integer stop String, array: true stream [ TrueClass, FalseClass ] frequency_penalty Float presence_penalty Float # openai variant of normalized properties for openai generative text endpoints max_completion_tokens Integer # openai properties for openai generative text endpoint audio do voice String format String end logit_bias logprobs [ TrueClass, FalseClass ] top_logprobs Integer modalities String, array: true response_format do # 'text' and 'json_schema' are the only supported types type Symbol, in: [ :text, :json_schema ] json_schema end service_tier String stream_options do include_usage [ TrueClass, FalseClass ] end user # open ai tools tool array: true, as: :tools, &Tool.schema # open ai tool choice configuration # # `tool_choice :none` # or # ``` # tool_choice :function do # function :my_function # end # ``` tool_choice arguments: :type do type Symbol, in: [ :none, :auto, :required ] function arguments: :name do name Symbol end end # the parallel_tool_calls parameter is only allowed when 'tools' are specified parallel_tool_calls [ TrueClass, FalseClass ] end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/open_ai.rb
lib/intelligence/adapters/open_ai.rb
require_relative '../adapter' require_relative 'open_ai/adapter'
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/generic/chat_request_methods.rb
lib/intelligence/adapters/generic/chat_request_methods.rb
module Intelligence module Generic module ChatRequestMethods module ClassMethods def chat_request_uri( uri = nil ) if uri @chat_request_uri = uri else @chat_request_uri end end end CHAT_COMPLETIONS_PATH = 'chat/completions' def self.included( base ) base.extend( ClassMethods ) end def chat_request_uri( options = nil ) options = merge_options( @options, build_options( options ) ) self.class.chat_request_uri || begin base_uri = options[ :base_uri ] if base_uri # because URI join is dumb base_uri = ( base_uri.end_with?( '/' ) ? base_uri : base_uri + '/' ) URI.join( base_uri, CHAT_COMPLETIONS_PATH ) else nil end end end def chat_request_headers( options = nil ) options = merge_options( @options, build_options( options ) ) result = { 'Content-Type': 'application/json' } key = options[ :key ] result[ 'Authorization' ] = "Bearer #{key}" if key result end def chat_request_body( conversation, options = nil ) tools = options.delete( :tools ) || [] options = merge_options( @options, build_options( options ) ) result = options[ :chat_options ] result[ :messages ] = [] system_message = chat_request_system_message_attributes( conversation[ :system_message ] ) result[ :messages ] << system_message if system_message conversation[ :messages ]&.each do | message | return nil unless message[ :contents ]&.any? result_message = { role: message[ :role ] } result_message_content = [] message_contents = message[ :contents ] # tool calls in the open ai api are not content tool_calls, message_contents = message_contents.partition do | content | content[ :type ] == :tool_call end # tool results in the open ai api are not content tool_results, message_contents = message_contents.partition do | content | content[ :type ] == :tool_result end # many vendor api's, especially when hosting text only models, will only accept a single # text content item; if the content is only text this will coalece multiple text content # items into a single content item unless message_contents.any? { | c | c[ :type ] != :text } result_message_content = message_contents.map { | c | c[ :text ] || '' }.join( "\n" ) else message_contents&.each do | content | result_message_content << chat_request_message_content_attributes( content ) end end if tool_calls.any? result_message[ :tool_calls ] = tool_calls.map { | tool_call | { id: tool_call[ :tool_call_id ], type: 'function', function: { name: tool_call[ :tool_name ], arguments: JSON.generate( tool_call[ :tool_parameters ] || {} ) } } } end result_message[ :content ] = result_message_content unless result_message_content.empty? && tool_calls.empty? result[ :messages ] << result_message end if tool_results.any? result[ :messages ].concat( tool_results.map { | tool_result | { role: :tool, name: tool_result[ :tool_name ], tool_call_id: tool_result[ :tool_call_id ], content: tool_result[ :tool_result ] } } ) end end tools_attributes = chat_request_tools_attributes( ( result[ :tools ] || [] ).concat( tools ) ) result[ :tools ] = tools_attributes if tools_attributes && tools_attributes.length > 0 JSON.generate( result ) end def chat_request_message_content_attributes( content ) case content[ :type ] when :text { type: 'text', text: content[ :text ] } when :binary content_type = content[ :content_type ] bytes = content[ :bytes ] if content_type && bytes mime_type = MIME::Types[ content_type ].first if mime_type&.media_type == 'image' { type: 'image_url', image_url: { url: "data:#{content_type};base64,#{Base64.strict_encode64( bytes )}".freeze } } else raise UnsupportedContentError.new( :generic, 'only support content of type image/*' ) end else raise UnsupportedContentError.new( :generic, 'requires binary content to include content type and ( packed ) bytes' ) end when :file content_type = content[ :content_type ] uri = content[ :uri ] if content_type && uri mime_type = MIME::Types[ content_type ].first if mime_type&.media_type == 'image' { type: 'image_url', image_url: { url: uri } } else raise UnsupportedContentError.new( :generic, 'only support content of type image/*' ) end else raise UnsupportedContentError.new( :generic, 'requires binary content to include content type and ( packed ) bytes' ) end end end def chat_request_system_message_attributes( system_message ) return nil if system_message.nil? result = '' system_message[ :contents ].each do | content | result += content[ :text ] if content[ :type ] == :text end result.empty? ? nil : { role: 'system', content: result } if system_message end def chat_request_tools_attributes( tools ) properties_array_to_object = lambda do | properties | return nil unless properties&.any? object = {} required = [] properties.each do | property | name = property.delete( :name ) required << name if property.delete( :required ) if property[ :properties ]&.any? property_properties, property_required = properties_array_to_object.call( property[ :properties ] ) property[ :properties ] = property_properties property[ :required ] = property_required if property_required.any? end object[ name ] = property end [ object, required.compact ] end Utilities.deep_dup( tools )&.map do | tool | function = { type: 'function', function: { name: tool[ :name ], description: tool[ :description ], } } if tool[ :properties ]&.any? properties_object, properties_required = properties_array_to_object.call( tool[ :properties ] ) function[ :function ][ :parameters ] = { type: 'object', properties: properties_object, required: [] } function[ :function ][ :parameters ][ :required ] = properties_required \ if properties_required.any? else function[ :function ][ :parameters ] = { type: 'object', properties: {}, required: [] } end function end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/generic/adapter.rb
lib/intelligence/adapters/generic/adapter.rb
require_relative '../../adapter' require_relative 'chat_request_methods' require_relative 'chat_response_methods' module Intelligence module Generic class Adapter < Adapter::Base include ChatRequestMethods include ChatResponseMethods end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/generic/chat_response_methods.rb
lib/intelligence/adapters/generic/chat_response_methods.rb
module Intelligence module Generic module ChatResponseMethods def chat_result_attributes( response ) return nil unless response.success? response_json = JSON.parse( response.body, symbolize_names: true ) rescue nil return nil if response_json.nil? || response_json[ :choices ].nil? result = {} result[ :choices ] = [] ( response_json[ :choices ] || [] ).each do | json_choice | end_reason = to_end_reason( json_choice[ :finish_reason ] ) if ( json_message = json_choice[ :message ] ) result_message = { role: json_message[ :role ] } if json_message[ :content ] result_message[ :contents ] = [ { type: :text, text: json_message[ :content ] } ] end if json_message[ :tool_calls ] && !json_message[ :tool_calls ].empty? result_message[ :contents ] ||= [] end_reason = :tool_called if end_reason == :ended json_message[ :tool_calls ].each do | json_message_tool_call | result_message_tool_call_parameters = JSON.parse( json_message_tool_call[ :function ][ :arguments ], symbolize_names: true ) \ rescue json_message_tool_call[ :function ][ :arguments ] result_message[ :contents ] << { type: :tool_call, tool_call_id: json_message_tool_call[ :id ], tool_name: json_message_tool_call[ :function ][ :name ], tool_parameters: result_message_tool_call_parameters } end end end result[ :choices ].push( { end_reason: end_reason, message: result_message } ) end metrics_json = response_json[ :usage ] unless metrics_json.nil? metrics = {} metrics[ :input_tokens ] = metrics_json[ :prompt_tokens ] metrics[ :output_tokens ] = metrics_json[ :completion_tokens ] metrics = metrics.compact result[ :metrics ] = metrics unless metrics.empty? end result end def chat_result_error_attributes( response ) error_type, error_description = to_error_response( response.status ) error = error_type parsed_body = JSON.parse( response.body, symbolize_names: true ) rescue nil if parsed_body && parsed_body.respond_to?( :[] ) if parsed_body[ :error ].respond_to?( :[] ) error = parsed_body[ :error ][ :code ] || error_type error_description = parsed_body[ :error ][ :message ] || error_description elsif parsed_body[ :object ] == 'error' error = parsed_body[ :type ] || error_type error_description = parsed_body[ :detail ] || parsed_body[ :message ] end end { error_type: error_type.to_s, error: error.to_s, error_description: error_description } end def stream_result_chunk_attributes( context, chunk ) context ||= {} buffer = context[ :buffer ] || '' metrics = context[ :metrics ] || { input_tokens: 0, output_tokens: 0 } choices = context[ :choices ] || Array.new( 1 , { message: {} } ) choices_delta = prune_choices( choices ) buffer += chunk while ( eol_index = buffer.index( "\n" ) ) line = buffer.slice!( 0..eol_index ) line = line.strip next if line.empty? || !line.start_with?( 'data:' ) line = line[ 6..-1 ] next if line.end_with?( '[DONE]' ) data = JSON.parse( line ) rescue nil if data.is_a?( Hash ) data[ 'choices' ]&.each do | data_choice | data_choice_index = data_choice[ 'index' ] data_choice_delta = data_choice[ 'delta' ] end_reason = to_end_reason( data_choice[ 'finish_reason' ] ) choices_delta.fill( { message: {} }, choices_delta.size, data_choice_index + 1 ) \ if choices.size <= data_choice_index contents = choices_delta[ data_choice_index ][ :message ][ :contents ] || [] if data_choice_content = data_choice_delta[ 'content' ] text_content = contents.last&.[]( :type ) == :text ? contents.last : nil if text_content.nil? contents.push( text_content = { type: :text, text: data_choice_content } ) else text_content[ :text ] = ( text_content[ :text ] || '' ) + data_choice_content end end if data_choice_tool_calls = data_choice_delta[ 'tool_calls' ] data_choice_tool_calls.each_with_index do | data_choice_tool_call, data_choice_tool_call_index | if data_choice_tool_call_function = data_choice_tool_call[ 'function' ] data_choice_tool_index = data_choice_tool_call[ 'index' ] || data_choice_tool_call_index data_choice_tool_id = data_choice_tool_call[ 'id' ] data_choice_tool_name = data_choice_tool_call_function[ 'name' ] data_choice_tool_parameters = data_choice_tool_call_function[ 'arguments' ] # if the data_choice_tool_id is present this indicates a new tool call. if data_choice_tool_id contents.push( { type: :tool_call, tool_call_id: data_choice_tool_id, tool_name: data_choice_tool_name, tool_parameters: data_choice_tool_parameters } ) # otherwise the tool is being aggregated else tool_call_content_index = contents.rindex do | content | content[ :type ] == :tool_call end tool_call = contents[ tool_call_content_index ] tool_call[ :tool_parameters ] = ( tool_call[ :tool_parameters ] || '' ) + data_choice_tool_parameters \ if data_choice_tool_parameters end end end end choices_delta[ data_choice_index ][ :message ][ :contents ] = contents choices_delta[ data_choice_index ][ :end_reason ] ||= end_reason end if usage = data[ 'usage' ] # note: A number of providers will resend the input tokens as part of their usage # payload. metrics[ :input_tokens ] = usage[ 'prompt_tokens' ] \ if usage.include?( 'prompt_tokens' ) metrics[ :output_tokens ] += usage[ 'completion_tokens' ] \ if usage.include?( 'completion_tokens' ) end end end context[ :buffer ] = buffer context[ :metrics ] = metrics context[ :choices ] = merge_choices!( choices, choices_delta ) [ context, { choices: choices_delta } ] end def stream_result_attributes( context ) context end alias_method :stream_result_error_attributes, :chat_result_error_attributes def to_end_reason( finish_reason ) case finish_reason when 'stop' :ended when 'length' :token_limit_exceeded when 'tool_calls' :tool_called when 'content_filter' :filtered else nil end end def to_error_response( status ) case status when 400 [ :invalid_request_error, "There was an issue with the format or content of your request." ] when 401 [ :authentication_error, "There's an issue with your API key." ] when 403 [ :permission_error, "Your API key does not have permission to use the specified resource." ] when 404 [ :not_found_error, "The requested resource was not found." ] when 413 [ :request_too_large, "Request exceeds the maximum allowed number of bytes." ] when 422 [ :invalid_request_error, "There was an issue with the format or content of your request." ] when 429 [ :rate_limit_error, "Your account has hit a rate limit." ] when 500, 502, 503 [ :api_error, "An unexpected error has occurred internal to the providers systems." ] when 529 [ :overloaded_error, "The providers server is temporarily overloaded." ] else [ :unknown_error, " An unknown error occurred." ] end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/open_ai/chat_request_methods.rb
lib/intelligence/adapters/open_ai/chat_request_methods.rb
module Intelligence module OpenAi module ChatRequestMethods CHAT_COMPLETIONS_PATH = 'responses' SUPPORTED_CONTENT_TYPES = [ 'image/jpeg', 'image/png', 'image/webp' ] def chat_request_uri( options = nil ) options = merge_options( @options, build_options( options ) ) base_uri = options[ :base_uri ] if base_uri # because URI join is dumb base_uri = ( base_uri.end_with?( '/' ) ? base_uri : base_uri + '/' ) URI.join( base_uri, CHAT_COMPLETIONS_PATH ) else raise 'The OpenAI adapter requires a base_uri.' end end def chat_request_headers( options = {} ) options = merge_options( @options, build_options( options ) ) result = {} key = options[ :key ] organization = options[ :organization ] project = options[ :project ] raise ArgumentError.new( "An OpenAI key is required to build an OpenAI chat request." ) \ if key.nil? result[ 'Content-Type' ] = 'application/json' result[ 'Authorization' ] = "Bearer #{key}" result[ 'OpenAI-Organization' ] = organization unless organization.nil? result[ 'OpenAI-Project' ] = project unless project.nil? result end def chat_request_body( conversation, options = {} ) tools = options.delete( :tools ) || [] # open ai abilities are essentially custom tools; when passed as an option they should # be in the open ai tool format ( which is essentially just a hash where the type is # the custome tool name ) # # { # abilities: [ # { type: 'web_search_preview' }, # { type: 'image_generation', background: 'transparent' }, # { type: 'local_shell' } # ] # } abilities = options.delete( :abilities ) || [] options = merge_options( @options, build_options( options ) ) result = options[ :chat_options ]&.compact || {} result[ :input ] = [] system_message = to_open_ai_system_message( conversation[ :system_message ] ) result[ :instructions ] = system_message if system_message conversation[ :messages ]&.each do | message | result_message = nil message[ :contents ]&.each do | content | case content[ :type ] when :text result_message = to_open_ai_message( message, id: content[ :'open_ai/id' ] ) \ if result_message.nil? result_message[ :content ] << { type: ( message[ :role ] == :user ? 'input_text' : 'output_text' ), text: content[ :text ] }.compact when :thought # nop when :cipher_thought open_ai_item = content[ :'open_ai/item' ] if open_ai_item if result_message result[ :input ] << result_message result_message = nil end result[ :input ] << JSON.parse( open_ai_item ) end when :binary result_message = to_open_ai_message( message ) if result_message.nil? content_type = content[ :content_type ] bytes = content[ :bytes ] if content_type && bytes if SUPPORTED_CONTENT_TYPES.include?( content_type ) result_message[ :content ] << { type: ( message[ :role ] == :user ? 'input_image' : 'output_image' ), id: content[ :'open_ai/id' ], image_url: "data:#{content_type};base64,#{Base64.strict_encode64( bytes )}".freeze }.compact else raise UnsupportedContentError.new( :open_ai, "only supports content of type #{SUPPORTED_CONTENT_TYPES.join( ', ' )}" ) end else raise UnsupportedContentError.new( :open_ai, 'requires binary content to include content type and ( packed ) bytes' ) end when :file result_message = to_open_ai_message( message ) if result_message.nil? content_type = content[ :content_type ] uri = content[ :uri ] if content_type && uri if SUPPORTED_CONTENT_TYPES.include?( content_type ) result_message[ :content ] << { type: ( message[ :role ] == :user ? 'input_image' : 'output_image' ), image_url: uri }.compact else raise UnsupportedContentError.new( :open_ai, "only supports content of type #{SUPPORTED_CONTENT_TYPES.join( ', ' )}" ) end else raise UnsupportedContentError.new( :open_ai, 'requires file content to include content type and uri' ) end when :tool_call if result_message result[ :input ] << result_message result_message = nil end result[ :input ] << { type: 'function_call', id: content[ :'open_ai/id' ], call_id: content[ :tool_call_id ], name: content[ :tool_name ], arguments: JSON.generate( content[ :tool_parameters ] || {} ) }.compact when :tool_result if result_message result[ :input ] << result_message result_message = nil end result[ :input ] << { type: 'function_call_output', call_id: content[ :tool_call_id ], output: content[ :tool_result ]&.to_s } when :web_search_call if result_message result[ :input ] << result_message result_message = nil end result[ :input ] << { id: content[ :'open_ai/id' ], type: 'web_search_call', action: { type: 'search', query: content[ :query ] } } when :web_reference # nop else raise UnsupportedContentError.new( :open_ai, "requires a known content type; received `#{content[ :type ]}`" ) end end result[ :input ] << result_message if result_message end tools_attributes = chat_request_tools_attributes( ( result[ :tools ] || [] ).concat( tools ) ) abilities.concat( result.delete( :abilities )&.values || [] ) tools_attributes.concat( abilities ) result[ :tools ] = tools_attributes if tools_attributes && tools_attributes.length > 0 JSON.generate( result ) end def chat_request_tools_attributes( tools ) properties_array_to_object = lambda do | properties | return nil unless properties&.any? object = {} required = [] properties.each do | property | name = property.delete( :name ) required << name if property.delete( :required ) if property[ :properties ]&.any? property_properties, property_required = properties_array_to_object.call( property[ :properties ] ) property[ :properties ] = property_properties property[ :required ] = property_required if property_required.any? end object[ name ] = property end [ object, required.compact ] end Utilities.deep_dup( tools )&.map do | tool | function = { type: 'function', name: tool[ :name ], description: tool[ :description ], } if tool[ :properties ]&.any? properties_object, properties_required = properties_array_to_object.call( tool[ :properties ] ) function[ :parameters ] = { type: 'object', properties: properties_object } function[ :parameters ][ :required ] = properties_required \ if properties_required.any? end function end end private def to_open_ai_system_message( system_message ) return nil if system_message.nil? result = '' system_message[ :contents ].each do | content | result += content[ :text ] if content[ :type ] == :text end result.empty? ? nil : result end def to_open_ai_message( message, id: nil ) open_ai_message = { role: message[ :role ], content: [], type: 'message' } open_ai_message[ :id ] = id if id open_ai_message end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/open_ai/adapter.rb
lib/intelligence/adapters/open_ai/adapter.rb
require_relative 'chat_request_methods' require_relative 'chat_response_methods' module Intelligence module OpenAi class Adapter < Adapter::Base DEFAULT_BASE_URI = 'https://api.openai.com/v1' schema do # normalized properties, used by all endpoints base_uri String, default: DEFAULT_BASE_URI key String # openai properties, used by all endpoints organization String project String chat_options do model String, requried: true background [ TrueClass, FalseClass ] include String, array: true, in: [ 'file_search_call.results', 'message.input_image.image_url', 'computer_call_output.output.image_url', 'reasoning.encrypted_content', 'code_interpreter_call.outputs' ] instructions String max_tokens Integer, as: :max_output_tokens metadata Hash previous_response_id String prompt do id String variables Hash version String end reasoning do effort Symbol, in: [ :low, :medium, :high ] summary Symbol, in: [ :auto, :concise, :detailed ] end service_tier Symbol, in: [ :auto, :default, :priority, :flex ] store [ TrueClass, FalseClass ] stream [ TrueClass, FalseClass ] temperature Float, in: 0..2 text do format Symbol, in: [ :text, :json_schema ] # these fields only apply when format is json_schema json_schema do name String schema required: true description String strict [ TrueClass, FalseClass ] end end top_p Float truncation Symbol, in: [ :auto, :disabled ] user String max_tool_calls Integer, in: (1..) parallel_tool_calls [ TrueClass, FalseClass ] tool_choice arguments: :type do type Symbol, in: [ :none, :auto, :required ] function arguments: :name do name Symbol end end tool array: true, as: :tools, &Tool.schema # build in open ai tools abilities do image_generation do type String, default: 'image_generation' background in: [ :transparent, :opaque, :auto ] model String moderation String output_compression Integer output_format Symbol, in: [ :png, :webp, :jpeg ] partial_images Integer quality Symbol, in: [ :auto, :low, :medium, :high ] size String, in: [ 'auto', '1024x1024', '1024x1536', '1536x1024' ] end local_shell do type String, default: 'local_shell' end code_interpreter do container_id String container do type String, default: 'auto' file_ids String, array: true end end web_search do type String, default: 'web_search_preview' search_context_size Symbol, in: [ :low, :medium, :high ] user_location do type Symbol, default: :approximate city String country String region String timezone String end end computer_use do type default: 'computer_use_preview' display_height Integer, requried: true display_width Integer, requried: true end end # openai variant of normalized properties for openai generative text endpoints max_output_tokens Integer end end include ChatRequestMethods include ChatResponseMethods end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/open_ai/chat_response_methods.rb
lib/intelligence/adapters/open_ai/chat_response_methods.rb
module Intelligence module OpenAi module ChatResponseMethods def chat_result_attributes( response ) return nil unless response.success? response_json = JSON.parse( response.body, symbolize_names: true ) rescue nil return nil if response_json.nil? result = { id: response_json[ :id ], user: response_json[ :user ] } result[ :choices ] = [] end_reason = translate_end_result( response_json ) json_output = response_json[ :output ] result_message = { role: 'assistant', contents: [] } json_output&.each do | json_payload | case json_payload[ :type ] when 'reasoning' json_payload[ :summary ]&.each do | json_content | case json_content[ :type ] when 'summary_text' result_message[ :contents ] << { type: :thought, text: json_content[ :text ] } end end if encrypted_content = json_payload[ :encrypted_content ] # The Open AI response API insists on this item being identical to the sent # item so we encode the entire item ( including the actual cipher ) and then # decode back to JSON when sending. result_message[ :contents ] << { type: :cipher_thought, :'open_ai/item' => json_payload.to_json } end when 'message' json_payload[ :content ]&.each do | json_content | case json_content[ :type ] when 'output_text' result_message[ :contents ] << { type: :text, :'open_ai/id' => json_payload[ :id ], text: json_content[ :text ] } json_content[ :annotations ]&.each do | json_annotation | result_message[ :contents ] << { type: :web_reference, uri: json_annotation[ :url ], title: json_annotation[ :title ] } end end end when 'function_call' end_reason = :tool_called if end_reason == :ended result_message_tool_call_parameters = nil if json_payload[ :arguments ] result_message_tool_call_parameters = json_payload[ :arguments ] begin result_message_tool_call_parameters = JSON.parse( json_payload[ :arguments ], symbolize_names: true ) rescue end end result_message[ :contents ] << { type: :tool_call, :'open_ai/id' => json_payload[ :id ], tool_call_id: json_payload[ :call_id ], tool_name: json_payload[ :name ], tool_parameters: result_message_tool_call_parameters } when 'web_search_call' web_search_action = json_payload[ :action ] || {} result_message[ :contents ] << { type: :web_search_call, :'open_ai/id' => json_payload[ :id ], query: web_search_action[ :query ], status: :complete } end end result[ :choices ].push( { end_reason: end_reason, message: result_message } ) metrics_json = response_json[ :usage ] unless metrics_json.nil? metrics = {} metrics[ :input_tokens ] = metrics_json[ :input_tokens ] metrics[ :output_tokens ] = metrics_json[ :output_tokens ] metrics = metrics.compact result[ :metrics ] = metrics unless metrics.empty? end result end def chat_result_error_attributes( response ) error_type, error_description = translate_error_response_status( response.status ) result = { error_type: error_type.to_s, error_description: error_description } parsed_body = JSON.parse( response.body, symbolize_names: true ) rescue nil if parsed_body && parsed_body.respond_to?( :include? ) && parsed_body.include?( :error ) result = { id: parsed_body[ :id ], user: parsed_body[ :user ], error_type: error_type.to_s, error: parsed_body[ :error ][ :code ] || error_type.to_s, error_description: parsed_body[ :error ][ :message ] || error_description } end result end def stream_result_chunk_attributes( context, chunk ) context ||= {} buffer = context[ :buffer ] || '' metrics = context[ :metrics ] || { input_tokens: 0, output_tokens: 0 } choices = context[ :choices ] || Array.new( 1 , { message: { contents: [] } } ) choices_delta = prune_choices( choices ) # the open ai responses api only ever return only 1 intelligence choice with 1 message choice = choices_delta.last message = choice[ :message ] contents = message[ :contents ] || [] annotations = [] buffer += chunk while ( eol_index = buffer.index( "\n" ) ) line = buffer.slice!( 0..eol_index ) line = line.strip next if line.empty? || !line.start_with?( 'data:' ) line = line[ 6..-1 ] next if line.end_with?( '[DONE]' ) data = JSON.parse( line, symbolize_names: true ) rescue nil #puts line # empty content is suppressed content = last_content = contents.last content_present = false if data.is_a?( Hash ) case data[ :type ] when 'response.output_item.added' response_item = data[ :item ] response_item_id = response_item[ :id ] case response_item[ :type ] # tool_call when 'function_call' content = { :'open_ai/cid' => "tool_call/#{response_item_id}/0", :'open_ai/id' => response_item_id, type: :tool_call, tool_name: response_item[ :name ], tool_call_id: response_item[ :call_id ], tool_parameters: response_item[ :arguments ] } content_present = true # web_search_call when 'web_search_call' content = { :'open_ai/cid' => "web_search_call/#{response_item_id}/0", :'open_ai/id' => response_item_id, type: :web_search_call, status: :searching } content_present = true end when 'response.function_call_arguments.delta' raise 'A function call argument delta was received but there is not tool content.' \ unless content and content[ :type ] == :tool_call ( content[ :tool_parameters ] ||= '' ) << data[ :delta ] # thought when 'response.reasoning_summary_part.added' response_cid = "thought/#{data[ :item_id ]}/#{data[ :summary_index ]}" response_part_json = data[ :part ] raise 'A reasoning content item was created but it is not `summary_text`.' \ if response_part_json[ :type ] != 'summary_text' response_text = response_part_json[ :text ] if content.nil? || content[ :'open_ai/cid' ] != response_cid content = { :'open_ai/cid' => response_cid, type: :thought, text: response_text || '' } content_present = response_text && response_text.length > 0 end when 'response.reasoning_summary_text.delta' response_cid = "thought/#{data[ :item_id ]}/#{data[ :summary_index ]}" response_text = data[ :delta ] if content.nil? || content[ :'open_ai/cid' ] != response_cid content = { :'open_ai/cid' => response_cid, type: :thought, text: response_text || '' } content_present = response_text && response_text.length > 0 else content_present = ( ( content[ :text ] ||= '' ) << response_text ).size.positive? end # text when 'response.content_part.added' response_item_id = data[ :item_id ] response_cid = "text/#{response_item_id}/#{data[ :content_index ]}" response_part_json = data[ :part ] raise 'A content item was created but it is not `output_text`.' \ if response_part_json[ :type ] != 'output_text' response_text = response_part_json[ :text ] if content.nil? || content[ :'open_ai/cid' ] != response_cid content = { :'open_ai/cid' => response_cid, :'open_ai/id' => response_item_id, type: :text, text: response_text || '' } content_present = response_text && response_text.length > 0 end when 'response.output_text.delta' response_item_id = data[ :item_id ] response_cid = "text/#{response_item_id}/#{data[ :content_index ]}" response_text = data[ :delta ] if content.nil? || content[ :'open_ai/cid' ] != response_cid content = { :'open_ai/cid' => response_cid, :'open_ai/id' => response_item_id, type: :text, text: response_text || '' } content_present = response_text && response_text.length > 0 else content_present = ( ( content[ :text ] ||= '' ) << response_text ).size.positive? end when 'response.output_item.done' response_item = data[ :item ] case response_item[ :type ] # text when 'message' if response_item_contents = response_item[ :content ] response_item_contents.each do | response_item_content | if response_item_annotations = response_item_content[ :annotations ] response_item_annotations.each do | response_item_annotation | if response_item_annotation[ :type ] == 'url_citation' annotations << { type: :web_reference, title: response_item_annotation[ :title ], uri: response_item_annotation[ :url ] } end end end end end # cipher thought when 'reasoning' response_item_id = response_item[ :id ] response_item_encrypted_content = response_item[ :encrypted_content ] if response_item_encrypted_content && response_item_encrypted_content.length > 0 content = { :'open_ai/cid' => "cipher_thought/#{response_item_id}/0", type: :cipher_thought, :'open_ai/id' => response_item_id, :'open_ai/item'=> response_item.to_json } content_present = true end # web search complete when 'web_search_call' raise 'A web search call completed but there is web search call content.' \ unless content and content[ :type ] == :web_search_call web_search_call_action = response_item[ :action ] || {} content[ :query ] = web_search_call_action[ :query ] content[ :status ] = :complete end when 'response.completed', 'response.incomplete' response_json = data[ :response ] end_reason = translate_end_result( response_json ) choice[ :end_reason ] = end_reason choice[ :end_reason ] = :tool_called \ if end_reason == :ended && last_content[ :type ] == :tool_call metrics_json = response_json[ :usage ] unless metrics_json.nil? metrics = {} metrics[ :input_tokens ] = metrics_json[ :input_tokens ] metrics[ :output_tokens ] = metrics_json[ :output_tokens ] metrics = metrics.compact end end if ( ( !last_content || last_content[ :'open_ai/cid' ] != content[ :'open_ai/cid' ] ) && content_present ) contents.push( content ) end annotations.each { | annotation | contents.push( annotation ) } annotations = [] end end context[ :buffer ] = buffer context[ :metrics ] = metrics context[ :choices ] = merge_choices!( choices, choices_delta ) [ context, choices_delta.empty? ? nil : { choices: purge_choices!( choices_delta ) } ] end def stream_result_attributes( context ) { choices: purge_choices!( context[ :choices ] ), metrics: context[ :metrics ] } end alias_method :stream_result_error_attributes, :chat_result_error_attributes private def prune_choices( choices ) choices.map do | original_choice | pruned_choice = original_choice.dup original_message = original_choice[ :message ] || { } pruned_message = original_message.dup pruned_message[ :contents ] = original_message[ :contents ]&.map do | content | { type: content[ :type ], :'open_ai/cid' => content[ :'open_ai/cid' ] } end pruned_choice[ :message ] = pruned_message pruned_choice end end def purge_choices!( choices ) choices.each do | choice | choice.dig( :message, :contents )&.each do | content | content.delete( :'open_ai/cid' ) end end choices end def translate_end_result( response_json ) return :ended if response_json[ :status ] == 'completed' case response_json[ :status ] when 'incomplete' case ( response_json[ :incomplete_details ][ :reason ] rescue nil ) when 'max_output_tokens' :token_limit_exceeded end end end def translate_error_response_status( status ) case status when 400 [ :invalid_request_error, "There was an issue with the format or content of your request." ] when 401 [ :authentication_error, "There's an issue with your API key." ] when 403 [ :permission_error, "Your API key does not have permission to use the specified resource." ] when 404 [ :not_found_error, "The requested resource was not found." ] when 413 [ :request_too_large, "Request exceeds the maximum allowed number of bytes." ] when 422 [ :invalid_request_error, "There was an issue with the format or content of your request." ] when 429 [ :rate_limit_error, "Your account has hit a rate limit." ] when 500, 502, 503 [ :api_error, "An unexpected error has occurred internal to the providers systems." ] when 529 [ :overloaded_error, "The providers server is temporarily overloaded." ] else [ :unknown_error, " An unknown error occurred." ] end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/x_ai/chat_request_methods.rb
lib/intelligence/adapters/x_ai/chat_request_methods.rb
module Intelligence module XAi module ChatRequestMethods def chat_request_body( conversation, options = nil ) tools = options.delete( :tools ) || [] web_search_parameters = options.delete( :search_parameters ) || {} options = merge_options( @options, build_options( options ) ) result = options[ :chat_options ] result[ :messages ] = [] system_message = chat_request_system_message_attributes( conversation[ :system_message ] ) result[ :messages ] << system_message if system_message conversation[ :messages ]&.each do | message | return nil unless message[ :contents ]&.any? result_message = { role: message[ :role ] } result_message_content = [] message_contents = message[ :contents ] # tool calls in the open ai api are not content tool_calls, message_contents = message_contents.partition do | content | content[ :type ] == :tool_call end # tool results in the open ai api are not content tool_results, message_contents = message_contents.partition do | content | content[ :type ] == :tool_result end # many vendor api's, especially when hosting text only models, will only accept a single # text content item; if the content is only text this will coalece multiple text content # items into a single content item unless message_contents.any? { | c | c[ :type ] != :text } result_message_content = message_contents.map { | c | c[ :text ] || '' }.join( "\n" ) else message_contents&.each do | content | result_message_content << chat_request_message_content_attributes( content ) end end if tool_calls.any? result_message[ :tool_calls ] = tool_calls.map { | tool_call | { id: tool_call[ :tool_call_id ], type: 'function', function: { name: tool_call[ :tool_name ], arguments: JSON.generate( tool_call[ :tool_parameters ] || {} ) } } } end result_message[ :content ] = result_message_content unless result_message_content.empty? && tool_calls.empty? result[ :messages ] << result_message end if tool_results.any? result[ :messages ].concat( tool_results.map { | tool_result | { role: :tool, tool_call_id: tool_result[ :tool_call_id ], content: tool_result[ :tool_result ] } } ) end end tools_attributes = chat_request_tools_attributes( ( result[ :tools ] || [] ).concat( tools ) ) result[ :tools ] = tools_attributes if tools_attributes && tools_attributes.length > 0 ability_attributes = result[ :abilities ] if ability_attributes && ability_attributes[ :search_parameters ] result[ :search_parameters ] = ability_attributes[ :search_parameters ].merge( web_search_parameters ) end JSON.generate( result ) end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/x_ai/adapter.rb
lib/intelligence/adapters/x_ai/adapter.rb
require_relative 'chat_request_methods' require_relative 'chat_response_methods' module Intelligence module XAi class Adapter < Generic::Adapter DEFAULT_BASE_URI = "https://api.x.ai/v1" schema do base_uri String, default: DEFAULT_BASE_URI key String chat_options do model String frequency_penalty Float, in: -2..2 logit_bias Hash logprobs [ TrueClass, FalseClass ] max_tokens Integer n Integer presence_penalty Float, in: -2..2 reasoning_effort Symbol, in: [ :low, :high ] response_format seed Integer stop String, array: true stream [ TrueClass, FalseClass ] stream_options temperature Float, in: 0..2 tool array: true, as: :tools, &Tool.schema tool_choice top_logprobs Integer, in: 0..20 top_p Float user String abilities do web_search as: :search_parameters do mode Symbol, in: [ :auto, :on, :off ], default: :auto return_citations [ TrueClass, FalseClass ] from_date String to_date String max_search_results Integer, in: (1..) sources array: true do type Symbol, in: [ :web, :x, :news, :rss ], required: true # web only allowed_websites String, array: true # web and news excluded_websites String, array: true safe_search [ TrueClass, FalseClass ] # x x_handles String, array: true # rss links String, array: true end end end end end include ChatRequestMethods include ChatResponseMethods def chat_result_error_attributes( response ) error_type, error_description = to_error_response( response.status ) error = error_type parsed_body = JSON.parse( response.body, symbolize_names: true ) rescue nil if parsed_body && parsed_body.respond_to?( :[] ) error = parsed_body[ :code ] || error_type error_description = parsed_body[ :error ] || error_description end { error_type: error_type.to_s, error: error.to_s, error_description: error_description } end alias_method :stream_result_error_attributes, :chat_result_error_attributes end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/x_ai/chat_response_methods.rb
lib/intelligence/adapters/x_ai/chat_response_methods.rb
module Intelligence module XAi module ChatResponseMethods def chat_result_attributes( response ) return nil unless response.success? response_json = JSON.parse( response.body, symbolize_names: true ) rescue nil return nil if response_json.nil? || response_json[ :choices ].nil? # these are just randomly sitting on the root :eyeroll citations = response_json[ :citations ] result = {} result[ :choices ] = [] ( response_json[ :choices ] || [] ).each do | json_choice | end_reason = to_end_reason( json_choice[ :finish_reason ] ) if ( json_message = json_choice[ :message ] ) result_message = { role: json_message[ :role ], contents: [] } if json_message[ :reasoning_content ]&.length&.positive? result_message[ :contents ] << { type: :thought, text: json_message[ :reasoning_content ] } end if json_message[ :content ] result_message[ :contents ] << { type: :text, text: json_message[ :content ] } end citations&.each do | citation | result_message[ :contents ] << { type: :web_reference, uri: citation } end if json_message[ :tool_calls ] && !json_message[ :tool_calls ].empty? result_message[ :contents ] ||= [] end_reason = :tool_called if end_reason == :ended json_message[ :tool_calls ].each do | json_message_tool_call | result_message_tool_call_parameters = JSON.parse( json_message_tool_call[ :function ][ :arguments ], symbolize_names: true ) \ rescue json_message_tool_call[ :function ][ :arguments ] result_message[ :contents ] << { type: :tool_call, tool_call_id: json_message_tool_call[ :id ], tool_name: json_message_tool_call[ :function ][ :name ], tool_parameters: result_message_tool_call_parameters } end end end result[ :choices ].push( { end_reason: end_reason, message: result_message } ) end metrics_json = response_json[ :usage ] unless metrics_json.nil? metrics = {} metrics[ :input_tokens ] = metrics_json[ :prompt_tokens ] metrics[ :output_tokens ] = metrics_json[ :completion_tokens ] metrics = metrics.compact result[ :metrics ] = metrics unless metrics.empty? end result end def stream_result_chunk_attributes( context, chunk ) context ||= {} buffer = context[ :buffer ] || '' metrics = context[ :metrics ] || { input_tokens: 0, output_tokens: 0 } choices = context[ :choices ] || Array.new( 1 , { message: {} } ) choices_delta = prune_choices( choices ) buffer += chunk while ( eol_index = buffer.index( "\n" ) ) line = buffer.slice!( 0..eol_index ) line = line.strip next if line.empty? || !line.start_with?( 'data:' ) line = line[ 6..-1 ] next if line.end_with?( '[DONE]' ) data = JSON.parse( line ) rescue nil if data.is_a?( Hash ) data[ 'choices' ]&.each do | data_choice | data_choice_index = data_choice[ 'index' ] data_choice_delta = data_choice[ 'delta' ] finish_reason = data_choice[ 'finish_reason' ] end_reason = to_end_reason( finish_reason ) if finish_reason choices_delta.fill( { message: {} }, choices_delta.size, data_choice_index + 1 ) \ if choices_delta.size <= data_choice_index contents = choices_delta[ data_choice_index ][ :message ][ :contents ] || [] if data_choice_reasoning_content = data_choice_delta[ 'reasoning_content' ] thought_content = contents.last&.[]( :type ) == :thought ? contents.last : nil if thought_content.nil? contents.push( { type: :thought, text: data_choice_reasoning_content } ) else thought_content[ :text ] = ( thought_content[ :text ] || '' ) + data_choice_reasoning_content end end if data_choice_content = data_choice_delta[ 'content' ] text_content = contents.last&.[]( :type ) == :text ? contents.last : nil if text_content.nil? contents.push( text_content = { type: :text, text: data_choice_content } ) else text_content[ :text ] = ( text_content[ :text ] || '' ) + data_choice_content end end if data_choice_tool_calls = data_choice_delta[ 'tool_calls' ] data_choice_tool_calls.each_with_index do | data_choice_tool_call, data_choice_tool_call_index | if data_choice_tool_call_function = data_choice_tool_call[ 'function' ] data_choice_tool_index = data_choice_tool_call[ 'index' ] || data_choice_tool_call_index data_choice_tool_id = data_choice_tool_call[ 'id' ] data_choice_tool_name = data_choice_tool_call_function[ 'name' ] data_choice_tool_parameters = data_choice_tool_call_function[ 'arguments' ] # if the data_choice_tool_id is present this indicates a new tool call. if data_choice_tool_id contents.push( { type: :tool_call, tool_call_id: data_choice_tool_id, tool_name: data_choice_tool_name, tool_parameters: data_choice_tool_parameters } ) # otherwise the tool is being aggregated else tool_call_content_index = contents.rindex do | content | content[ :type ] == :tool_call end tool_call = contents[ tool_call_content_index ] if data_choice_tool_parameters tool_call[ :tool_parameters ] = ( tool_call[ :tool_parameters ] || '' ) + data_choice_tool_parameters end end end end end # the citations are awkwardly placed on the root of the response payload but their # actually specific to the choice/message; the grok api only ever returns one choice # and one messages per choice though so :shrug data[ 'citations' ]&.each do | citation | contents << { type: :web_reference, uri: citation } end choices_delta[ data_choice_index ][ :message ][ :contents ] = contents choices_delta[ data_choice_index ][ :end_reason ] ||= end_reason end if usage = data[ 'usage' ] # note: A number of providers will resend the input tokens as part of their usage # payload. metrics[ :input_tokens ] = usage[ 'prompt_tokens' ] \ if usage.include?( 'prompt_tokens' ) metrics[ :output_tokens ] += usage[ 'completion_tokens' ] \ if usage.include?( 'completion_tokens' ) end end end context[ :buffer ] = buffer context[ :metrics ] = metrics context[ :choices ] = merge_choices!( choices, choices_delta ) [ context, choices_delta.empty? ? nil : { choices: choices_delta } ] end def chat_result_error_attributes( response ) error_type, error_description = to_error_response( response.status ) error = error_type parsed_body = JSON.parse( response.body, symbolize_names: true ) rescue nil if parsed_body && parsed_body.respond_to?( :[] ) error = parsed_body[ :code ] || error_type error_description = parsed_body[ :error ] || error_description end { error_type: error_type.to_s, error: error.to_s, error_description: error_description } end alias_method :stream_result_error_attributes, :chat_result_error_attributes end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/anthropic/extensions.rb
lib/intelligence/adapters/anthropic/extensions.rb
require_relative 'extensions/cache_control'
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/anthropic/chat_request_methods.rb
lib/intelligence/adapters/anthropic/chat_request_methods.rb
module Intelligence module Anthropic module ChatRequestMethods CHAT_REQUEST_URI = "https://api.anthropic.com/v1/messages" SUPPORTED_CONTENT_TYPES = %w[ image/jpeg image/png image/gif image/webp application/pdf ] def chat_request_uri( options ) CHAT_REQUEST_URI end def chat_request_headers( options = nil ) options = merge_options( @options, build_options( options ) ) result = {} key = options[ :key ] version = options[ :version ] || "2023-06-01" raise ArgumentError.new( "An Anthropic key is required to build an Anthropic chat request." ) if key.nil? result[ 'content-type' ] = 'application/json' result[ 'x-api-key' ] = "#{key}" result[ 'anthropic-version' ] = version unless version.nil? result end def chat_request_body( conversation, options = nil ) tools = options.delete( :tools ) || [] options = merge_options( @options, build_options( options ) ) result = options[ :chat_options ]&.compact || {} system_message = to_anthropic_system_message( conversation[ :system_message ] ) result[ :system ] = system_message unless system_message.nil? result[ :messages ] = [] messages = conversation[ :messages ] length = messages&.length || 0 index = 0; while index < length message = messages[ index ] unless message.nil? # The Anthropic API will not accept a sequence of messages where the role of two # sequentian messages is the same. # # The purpose of this code is to identify such occurences and coalece them such # that the first message in the sequence aggregates the contents of all subsequent # messages with the same role. look_ahead_index = index + 1; while look_ahead_index < length ahead_message = messages[ look_ahead_index ] unless ahead_message.nil? if ahead_message[ :role ] == message[ :role ] message[ :contents ] = ( message[ :contents ] || [] ) + ( ahead_message[ :contents ] || [] ) messages[ look_ahead_index ] = nil look_ahead_index += 1 else break end end end result_message = { role: message[ :role ] } result_message_contents = [] message[ :contents ]&.each do | content | cache_control = content[ :'anthropic/cache_control' ] case content[ :type ] when :text result_message_content = { type: 'text', text: content[ :text ] } result_message_content[ :cache_control ] = cache_control if cache_control result_message_contents << result_message_content when :thought signature = content[ :'anthropic/signature' ] if signature && signature.length > 0 result_message_contents << { type: 'thinking', thinking: content[ :text ], signature: signature } end when :cipher_thought # nop when :binary content_type = content[ :content_type ] bytes = content[ :bytes ] if content_type && bytes if SUPPORTED_CONTENT_TYPES.include?( content_type ) result_message_content = { type: content_type == 'application/pdf' ? 'document' : 'image', source: { type: 'base64', media_type: content_type, data: Base64.strict_encode64( bytes ) } } result_message_content[ :cache_control ] = cache_control if cache_control result_message_contents << result_message_content else raise UnsupportedContentError.new( :anthropic, 'only support content of type image/*' ) end else raise UnsupportedContentError.new( :anthropic, 'requires file content to include content type and (packed) bytes' ) end when :file content_type = content[ :content_type ] uri = content[ :uri ] if content_type && uri if SUPPORTED_CONTENT_TYPES.include?( content_type ) result_message_content = { type: content_type == 'application/pdf' ? 'document' : 'image', source: { type: 'url', url: uri } } result_message_content[ :cache_control ] = cache_control if cache_control result_message_contents << result_message_content else raise UnsupportedContentError.new( :anthropic, "only supports content of type #{SUPPORTED_CONTENT_TYPES.join( ', ' )}" ) end else raise UnsupportedContentError.new( :anthropic, 'requires file content to include content type and uri' ) end when :tool_call tool_parameters = content[ :tool_parameters ] tool_parameters = {} \ if tool_parameters.nil? || ( tool_parameters.is_a?( String ) && tool_parameters.empty? ) result_message_content = { type: 'tool_use', id: content[ :tool_call_id ], name: content[ :tool_name ], input: tool_parameters } result_message_content[ :cache_control ] = cache_control if cache_control result_message_contents << result_message_content when :tool_result result_message_content = { type: 'tool_result', tool_use_id: content[ :tool_call_id ], content: content[ :tool_result ]&.to_s } result_message_content[ :cache_control ] = cache_control if cache_control result_message_contents << result_message_content when :web_search_call, :web_reference # nop else raise UnsupportedContentError.new( :anthropic, "does not support content of type '#{content[ :type ]}'." ) end end result_message[ :content ] = result_message_contents result[ :messages ] << result_message end index += 1 end tools_attributes = chat_request_tools_attributes( ( result[ :tools ] || [] ).concat( tools ) ) result[ :tools ] = tools_attributes if tools_attributes && tools_attributes.length > 0 JSON.generate( result ) end def chat_request_tools_attributes( tools ) properties_array_to_object = lambda do | properties | return nil unless properties&.any? object = {} required = [] properties.each do | property | property = property.dup name = property.delete( :name ) required << name if property.delete( :required ) if property[ :properties ]&.any? property_properties, property_required = properties_array_to_object.call( property[ :properties ] ) property[ :properties ] = property_properties property[ :required ] = property_required if property_required.any? end object[ name ] = property end [ object, required.compact ] end tools&.map do | tool | tool_attributes = { name: tool[ :name ], description: tool[ :description ], input_schema: { type: 'object' } } if tool[ :properties ]&.any? properties_object, properties_required = properties_array_to_object.call( tool[ :properties ] ) input_schema = { type: 'object', properties: properties_object } input_schema[ :required ] = properties_required if properties_required.any? tool_attributes[ :input_schema ] = input_schema end tool_attributes end end private def to_anthropic_system_message( system_message ) return nil if system_message.nil? # note: the current version of the anthropic api simply takes a string as the # system message but the beta version requires an array of objects akin # to message contents. result = '' system_message[ :contents ].each do | content | result += content[ :text ] if content[ :type ] == :text end result.empty? ? nil : result end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/anthropic/adapter.rb
lib/intelligence/adapters/anthropic/adapter.rb
require_relative 'chat_request_methods' require_relative 'chat_response_methods' module Intelligence module Anthropic class Adapter < Adapter::Base schema do # normalized properties for all endpoints key # anthropic specific properties for all endpoints version String, default: '2023-06-01' chat_options do # normalized properties for anthropic generative text endpoint model String max_tokens Integer, in: (1...) temperature Float, in: 0.0..1.0 top_k Integer, in: (1...) top_p Float, in: (0..1) stop String, array: true, as: :stop_sequences stream [ TrueClass, FalseClass ] # anthropic variant of normalized properties for anthropic generative text endpoints stop_sequences String, array: true # anthropic reasoning reasoning as: :thinking do type Symbol, required: true, default: :enabled budget_tokens required: true, in: (1024...) # normalized attribute name budget as: :budget_tokens, in: (1024...) end # anthropic specific properties for anthropic generative text endpoints tool array: true, as: :tools, &Tool.schema # anthropic tool choice configuration; note that there is no 'none' option so if # tools are provided :auto will be the default # # `tool_choice :any` # or # ``` # tool_choice :tool do # function :my_tool # end # ``` tool_choice arguments: :type do type Symbol, in: [ :any, :auto, :tool ] # the name parameter should only be set if type = 'tool' name String end container String metadata do user_id String end service_tier Symbol, in: [ :auto, :standard_only ] end end include ChatRequestMethods include ChatResponseMethods end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/anthropic/chat_response_methods.rb
lib/intelligence/adapters/anthropic/chat_response_methods.rb
module Intelligence module Anthropic module ChatResponseMethods def chat_result_attributes( response ) return nil unless response.success? response_json = JSON.parse( response.body, symbolize_names: true ) rescue nil return nil if response_json.nil? result = {} result_choice = { end_reason: translate_end_result( response_json[ :stop_reason ] ), end_sequence: response_json[ :stop_sequence ], } if response_json[ :content ] && response_json[ :content ].is_a?( Array ) && !response_json[ :content ].empty? result_content = [] response_json[ :content ].each do | content | case content[ :type ] when 'text' result_content.push( { type: 'text', text: content[ :text ] } ) when 'thinking' result_content.push( { type: 'thought', text: content[ :thinking ], :'anthropic/signature' => content[ :signature ] } ) when 'tool_use' result_content.push( { type: :tool_call, tool_call_id: content[ :id ], tool_name: content[ :name ], tool_parameters: content[ :input ] } ) end end unless result_content.empty? result_choice[ :message ] = { role: response_json[ :role ] || 'assistant', contents: result_content } end end result[ :choices ] = [ result_choice ] metrics_json = response_json[ :usage ] unless metrics_json.nil? result_metrics = {} result_metrics[ :input_tokens ] = metrics_json[ :input_tokens ] result_metrics[ :output_tokens ] = metrics_json[ :output_tokens ] result_metrics[ :cache_write_input_tokens ] = metrics_json[ :cache_creation_input_tokens ] result_metrics[ :cache_read_input_tokens ] = metrics_json[ :cache_read_input_tokens ] result_metrics = result_metrics.compact result[ :metrics ] = result_metrics unless result_metrics.empty? end result end def chat_result_error_attributes( response ) error_type, error_description = translate_response_status( response.status ) parsed_body = JSON.parse( response.body, symbolize_names: true ) rescue nil if parsed_body && parsed_body.respond_to?( :include? ) && parsed_body.include?( :error ) result = { error_type: error_type.to_s, error: parsed_body[ :error ][ :type ], error_description: parsed_body[ :error ][ :message ] || error_description } elsif result = { error_type: error_type.to_s, error_description: error_description } end result end def stream_result_chunk_attributes( context, chunk ) context ||= {} buffer = context[ :buffer ] || '' choices = context[ :choices ] || Array.new( 1 , { message: { contents: [] } } ) metrics = context[ :metrics ] || { input_tokens: 0, output_tokens: 0, cache_write_input_tokens: 0, cache_read_input_tokens: 0 } end_reason = context[ :end_reason ] end_sequence = context[ :end_sequence ] contents = choices.first[ :message ][ :contents ] contents = contents.map do | content | { type: content[ :type ] } end buffer += chunk while ( eol_index = buffer.index( "\n" ) ) line = buffer.slice!( 0..eol_index ) line = line.strip next if line.empty? || !line.start_with?( 'data:' ) line = line[ 6..-1 ] data = JSON.parse( line ) #puts line case data[ 'type' ] when 'message_start' metrics[ :input_tokens ] += data[ 'message' ]&.[]( 'usage' )&.[]( 'input_tokens' ) || 0 metrics[ :output_tokens ] += data[ 'message' ]&.[]( 'usage' )&.[]( 'output_tokens' ) || 0 metrics[ :cache_write_input_tokens ] += data[ 'message' ]&.[]( 'usage' )&.[]( 'cache_creation_input_tokens' ) || 0 metrics[ :cache_read_input_tokens ] += data[ 'message' ]&.[]( 'usage' )&.[]( 'cache_read_input_tokens' ) || 0 when 'content_block_start' index = data[ 'index' ] if contents.size <= index contents.fill( contents.size..index ) { {} } end if content_block = data[ 'content_block' ] case content_block[ 'type' ] when 'text' contents[ index ] = { type: :text, text: content_block[ 'text' ] || '' } when 'thinking' contents[ index ] = { type: :thought, text: content_block[ 'thinking' ] || '' } when 'tool_use' contents[ index ] = { type: :tool_call, tool_name: content_block[ 'name' ], tool_call_id: content_block[ 'id' ], tool_parameters: '' } end end when 'content_block_delta' index = data[ 'index' ] contents.fill( {}, contents.size..index ) if contents.size <= index if delta = data[ 'delta' ] case delta[ 'type' ] when 'text_delta' contents[ index ][ :type ] = :text contents[ index ][ :text ] = ( contents[ index ][ :text ] || '' ) + delta[ 'text' ] when 'thinking_delta' contents[ index ][ :type ] = :thought contents[ index ][ :text ] = ( contents[ index ][ :text ] || '' ) + delta[ 'thinking' ] when 'signature_delta' if contents[ index ][ :type ] == :thought contents[ index ][ :'anthropic/signature' ] = delta[ 'signature' ] end when 'input_json_delta' contents[ index ][ :type ] = :tool_call contents[ index ][ :tool_parameters ] = ( contents[ index ][ :tool_parameters ] || '' ) + delta[ 'partial_json' ] end end when 'message_delta' if delta = data[ 'delta' ] end_reason = delta[ 'stop_reason' ] end_sequence = delta[ 'stop_sequence' ] end metrics[ :output_tokens ] += data[ 'usage' ]&.[]( 'output_tokens' ) || 0 when 'message_stop' end end choices_delta = [ { end_reason: translate_end_result( end_reason ), end_sequence: end_sequence, message: { contents: contents } } ] [ { buffer: buffer, choices: merge_choices!( choices, choices_delta ), end_reason: end_reason, end_sequence: end_sequence, metrics: metrics }, { choices: choices_delta } ] end def stream_result_attributes( context ) { choices: context[ :choices ], metrics: context[ :metrics ] } end alias_method :stream_result_error_attributes, :chat_result_error_attributes private def translate_end_result( end_result ) case end_result when 'end_turn' :ended when 'max_tokens' :token_limit_exceeded when 'stop_sequence' :end_sequence_encountered when 'tool_use' :tool_called else # if the result has already been translated, this simply returns it end_result end end def translate_response_status( status ) case status when 400 [ :invalid_request_error, "There was an issue with the format or content of your request." ] when 401 [ :authentication_error, "There's an issue with your API key." ] when 403 [ :permission_error, "Your API key does not have permission to use the specified resource." ] when 404 [ :not_found_error, "The requested resource was not found." ] when 413 [ :request_too_large, "Request exceeds the maximum allowed number of bytes." ] when 429 [ :rate_limit_error, "Your account has hit a rate limit." ] when 500 [ :api_error, "An unexpected error has occurred internal to Anthropic's systems." ] when 529 [ :overloaded_error, "Anthropic's API is temporarily overloaded." ] else [ :unknown_error, " An unknown error occurred." ] end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/anthropic/extensions/cache_control.rb
lib/intelligence/adapters/anthropic/extensions/cache_control.rb
module Intelligence module Anthropic module Extensions module MessageContent module CacheControl def cache_control @_cache_control end def cache_control=( value ) @_cache_control = case value when true, :ephemeral { type: 'ephemeral' } when false, nil nil when Hash value.transform_keys( &:to_s ) else { type: value.to_s } end end def cache_control_ttl @_cache_control && @_cache_control[ 'ttl' ] end def cache_control_ttl=( value ) if value.nil? @_cache_control&.delete( 'ttl' ) return end unless value.is_a?( Integer ) && [ 5, 60 ].include?( value ) raise ArgumentError, "cache_control_ttl must be 5 or 60 (minutes); received #{value.inspect}" end # Auto-initialize cache_control if the user sets TTL first self.cache_control = :ephemeral if @_cache_control.nil? # Store the value @_cache_control[ 'ttl' ] = value end def to_h hash = super hash[ :'anthropic/cache_control' ] = @_cache_control if @_cache_control hash end end end end end end Intelligence::MessageContent::Base.prepend( Intelligence::Anthropic::Extensions::MessageContent::CacheControl )
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/google/chat_request_methods.rb
lib/intelligence/adapters/google/chat_request_methods.rb
require 'uri' module Intelligence module Google module ChatRequestMethods GENERATIVE_LANGUAGE_URI = "https://generativelanguage.googleapis.com/v1beta/models/" SUPPORTED_BINARY_MEDIA_TYPES = %w[ text ] SUPPORTED_BINARY_CONTENT_TYPES = %w[ image/png image/jpeg image/webp image/heic image/heif audio/aac audio/flac audio/mp3 audio/m4a audio/mpeg audio/mpga audio/mp4 audio/opus audio/pcm audio/wav audio/webm application/pdf ] SUPPORTED_FILE_MEDIA_TYPES = %w[ text ] SUPPORTED_FILE_CONTENT_TYPES = %w[ image/png image/jpeg image/webp image/heic image/heif video/x-flv video/quicktime video/mpeg video/mpegps video/mpg video/mp4 video/webm video/wmv video/3gpp audio/aac audio/flac audio/mp3 audio/m4a audio/mpeg audio/mpga audio/mp4 audio/opus audio/pcm audio/wav audio/webm application/pdf ] def chat_request_uri( options ) options = merge_options( @options, build_options( options ) ) key = options[ :key ] gc = options[ :generationConfig ] || {} model = gc[ :model ] stream = gc.key?( :stream ) ? gc[ :stream ] : false raise ArgumentError.new( "A Google API key is required to build a Google chat request." ) \ if key.nil? raise ArgumentError.new( "A Google model is required to build a Google chat request." ) \ if model.nil? uri = URI( GENERATIVE_LANGUAGE_URI ) path = File.join( uri.path, model ) path += stream ? ':streamGenerateContent' : ':generateContent' uri.path = path query = { key: key } query[ :alt ] = 'sse' if stream uri.query = URI.encode_www_form( query ) uri.to_s end def chat_request_headers( options = {} ) { 'Content-Type' => 'application/json' } end def chat_request_body( conversation, options = {} ) tools = options.delete( :tools ) || [] options = merge_options( @options, build_options( options ) ) gc = options[ :generationConfig ]&.dup || {} # discard properties not part of the google generationConfig schema gc.delete( :model ) gc.delete( :stream ) # googlify tools tools_object = gc.delete( :abilities ) tool_functions = to_google_tools( ( gc.delete( :tools ) || [] ).concat( tools ) ) if tool_functions&.any? tools_object ||= {} tools_object[ :function_declarations ] ||= [] tools_object[ :function_declarations ].concat( tool_functions ) end # googlify tool configuration if tool_config = gc.delete( :tool_config ) mode = tool_config[ :function_calling_config ]&.[]( :mode ) tool_config[ :function_calling_config ][ :mode ] = mode.to_s.upcase if mode end result = {} result[ :generationConfig ] = gc result[ :tools ] = tools_object if tools_object result[ :tool_config ] = tool_config if tools && tool_config # construct the system prompt in the form of the google schema system_instructions = to_google_system_message( conversation[ :system_message ] ) result[ :systemInstruction ] = system_instructions if system_instructions result[ :contents ] = [] conversation[ :messages ]&.each do | message | result_message = { role: message[ :role ] == :user ? 'user' : 'model' } result_message_parts = [] thought_signature = nil message[ :contents ]&.each do | content | case content[ :type ] when :text text_part = { text: content[ :text ] } if ( thought_signature ) text_part[ :thoughtSignature ] = thought_signature thought_signature = nil end result_message_parts << text_part when :binary content_type = content[ :content_type ] bytes = content[ :bytes ] if content_type && bytes mime_type = MIME::Types[ content_type ].first if SUPPORTED_BINARY_MEDIA_TYPES.include?( mime_type&.media_type ) || SUPPORTED_BINARY_CONTENT_TYPES.include?( content_type ) binary_part = { inline_data: { mime_type: content_type, data: Base64.strict_encode64( bytes ) } } if ( thought_signature ) binary_part[ :thoughtSignature ] = thought_signature thought_signature = nil end result_message_parts << binary_part else raise UnsupportedContentError.new( :google, "does not support #{content_type} content type" ) end else raise UnsupportedContentError.new( :google, 'requires binary content to include content type and ( packed ) bytes' ) end when :file content_type = content[ :content_type ] uri = content[ :uri ] if content_type && uri mime_type = MIME::Types[ content_type ].first if SUPPORTED_FILE_MEDIA_TYPES.include?( mime_type&.media_type ) || SUPPORTED_FILE_CONTENT_TYPES.include?( content_type ) file_part = { file_data: { mime_type: content_type, file_uri: uri } } if ( thought_signature ) file_part[ :thoughtSignature ] = thought_signature thought_signature = nil end result_message_parts << file_part else raise UnsupportedContentError.new( :google, "does not support #{content_type} content type" ) end else raise UnsupportedContentError.new( :google, 'requires file content to include content type and uri' ) end when :tool_call tool_call_part = { functionCall: { name: content[ :tool_name ], args: content[ :tool_parameters ] } } if ( thought_signature ) tool_call_part[ :thoughtSignature ] = thought_signature thought_signature = nil end result_message_parts << tool_call_part when :tool_result result_message_parts << { functionResponse: { name: content[ :tool_name ], response: { name: content[ :tool_name ], content: content[ :tool_result ] } } } when :thought # nop when :cipher_thought # google thought signature are packed with an arbitrary part so the cipher from a # cipher thought is stored to be included in the subsequent part thought_signature = content[ :'google/thought-signature' ] when :web_search_call, :web_reference #nop else raise UnsupportedContentError.new( :google ) end end result_message[ :parts ] = result_message_parts result[ :contents ] << result_message end JSON.generate( result ) end private def to_google_system_message( system_message ) return nil if system_message.nil? text = '' system_message[ :contents ].each do | content | text += content[ :text ] if content[ :type ] == :text end return nil if text.empty? { role: 'user', parts: [ { text: text } ] } end def to_google_tools( tools ) properties_array_to_object = lambda do | properties | return nil unless properties&.any? object = {} required = [] properties.each do | property | name = property.delete( :name ) required << name if property.delete( :required ) if property[ :properties ]&.any? property_properties, property_required = properties_array_to_object.call( property[ :properties ] ) property[ :properties ] = property_properties property[ :required ] = property_required if property_required.any? end object[ name ] = property end [ object, required.compact ] end return Utilities.deep_dup( tools )&.map { | tool | function = { name: tool[ :name ], description: tool[ :description ], } if tool[ :properties ]&.any? properties_object, properties_required = properties_array_to_object.call( tool[ :properties ] ) function[ :parameters ] = { type: 'object', properties: properties_object } function[ :parameters ][ :required ] = properties_required if properties_required.any? end function } end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/google/adapter.rb
lib/intelligence/adapters/google/adapter.rb
require_relative 'chat_request_methods' require_relative 'chat_response_methods' module Intelligence module Google class Adapter < Adapter::Base schema do # normalized properties for all endpoints key String chat_options as: :generationConfig do # normalized properties for google generative text endpoint model String max_tokens Integer, as: :maxOutputTokens n Integer, as: :candidateCount temperature Float top_k Integer, as: :topK top_p Float, as: :topP seed Integer stop String, array: true, as: :stopSequences stream [ TrueClass, FalseClass ] frequency_penalty Float, as: :frequencyPenalty presence_penalty Float, as: :presencePenalty # google variant of normalized properties for google generative text endpoints candidate_count Integer, as: :candidateCount max_output_tokens Integer, as: :maxOutputTokens stop_sequences String, array: true, as: :stopSequences # google specific properties for google generative text endpoints response_mime_type String, as: :responseMimeType response_schema as: :responseSchema # google specific thinking properies reasoning as: :thinkingConfig, default: {} do # gemini 2 and 2.5 models thinking_budget Integer, as: :thinkingBudget, in:(-1...) # gemini 3 models thinking_level String, as: :thinkingLevel, in:['HIGH','LOW'] # gemini 2, 2.5 and 3 models include_thoughts [ TrueClass, FalseClass ], as: :includeThoughts # normalized properties # gemini 2 and 2.5 models budget Integer, as: :thinkingBudget, in:(-1...) # gemini 3 models effort Integer, as: :thinkingLevel, in:['HIGH','LOW'] # gemini 2, 2.5 and 3 models summary [ TrueClass, FalseClass ], as: :includeThoughts end # google specific tool configuration tool array: true, as: :tools, &Tool.schema tool_configuration as: :tool_config do function_calling as: :function_calling_config do mode Symbol, in: [ :auto, :any, :none ] allowed_function_names String, array: true end end # build-in tools are called 'abilities' in Intelligence so as not to conflic # with the caller defined tools abilities do web_search as: :googleSearch do; end web_browser as: :urlContext do; end code_execution as: :codeExecution do; end end end end include ChatRequestMethods include ChatResponseMethods end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapters/google/chat_response_methods.rb
lib/intelligence/adapters/google/chat_response_methods.rb
require 'uri' module Intelligence module Google module ChatResponseMethods def chat_result_attributes( response ) return nil unless response.success? response_json = JSON.parse( response.body, symbolize_names: true ) rescue nil return nil if response_json.nil? || response_json[ :candidates ].nil? result = {} result[ :choices ] = [] response_json[ :candidates ]&.each do | response_choice | end_reason = translate_finish_reason( response_choice[ :finishReason ] ) role = nil contents = [] response_content = response_choice[ :content ] if response_content role = ( response_content[ :role ] == 'model' ) ? 'assistant' : 'user' contents = [] response_content[ :parts ]&.each do | response_content_part | # google encrypted thoughts are included in other ( seemingly arbitrary ) # content so create a cipher_thought before the content to make it easier # to pack it in future requests if response_content_part.key?( :thoughtSignature ) contents.push( { type: :cipher_thought, :'google/thought-signature' => response_content_part[ :thoughtSignature ] } ) end if response_content_part.key?( :text ) type = response_content_part[ :thought ] ? :thought : :text contents.push( { type: type, text: response_content_part[ :text ] } ) elsif function_call = response_content_part[ :functionCall ] contents.push( { type: :tool_call, tool_name: function_call[ :name ], tool_parameters: function_call[ :args ] } ) # google does not indicate there is tool call in the stop reason so # we will synthesize this end reason end_reason = :tool_called if end_reason == :ended end end end result_message = nil if role result_message = { role: role } result_message[ :contents ] = contents end result[ :choices ].push( { end_reason: end_reason, message: result_message } ) end metrics_json = response_json[ :usageMetadata ] unless metrics_json.nil? metrics = {} metrics[ :input_tokens ] = metrics_json[ :promptTokenCount ] metrics[ :output_tokens ] = metrics_json[ :candidatesTokenCount ] metrics = metrics.compact result[ :metrics ] = metrics unless metrics.empty? end result end def chat_result_error_attributes( response ) error_type, error_description = translate_error_response_status( response.status ) result = { error_type: error_type.to_s, error_description: error_description } response_body = JSON.parse( response.body, symbolize_names: true ) rescue nil if response_body && response_body[ :error ] error_details_reason = response_body[ :error ][ :details ]&.first&.[]( :reason ) # a special case for authentication error_type = :authentication_error if error_details_reason == 'API_KEY_INVALID' error = error_details_reason || response_body[ :error ][ :status ] || error_type result = { error_type: error_type.to_s, error: error.to_s, error_description: response_body[ :error ][ :message ] } end result end def stream_result_chunk_attributes( context, chunk ) context ||= {} buffer = context[ :buffer ] || '' metrics = context[ :metrics ] || { input_tokens: 0, output_tokens: 0 } choices = context[ :choices ] || Array.new( 1 , { message: {} } ) choices_delta = prune_choices( choices ) buffer += chunk while ( eol_index = buffer.index( "\n" ) ) line = buffer.slice!( 0..eol_index ) line = line.strip next if line.empty? || !line.start_with?( 'data:' ) line = line[ 6..-1 ] data = JSON.parse( line, symbolize_names: true ) # puts line if data.is_a?( Hash ) data[ :candidates ]&.each do | data_candidate | data_candidate_index = data_candidate[ :index ] || 0 data_candidate_content = data_candidate[ :content ] data_candidate_finish_reason = data_candidate[ :finishReason ] if choices_delta.size <= data_candidate_index choices_delta.fill( { message: { role: 'assistant' } }, choices_delta.size, data_candidate_index + 1 ) end contents = choices_delta[ data_candidate_index ][ :message ][ :contents ] || [] last_content = contents&.last if data_candidate_content&.include?( :parts ) data_candidate_content_parts = data_candidate_content[ :parts ] data_candidate_content_parts&.each do | data_candidate_content_part | # google encrypted thoughts are included in other ( seemingly arbitrary ) # content so create a cipher_thought before the content to make it easier # to pack it in future requests if data_candidate_content_part.key?( :thoughtSignature ) contents.push( { type: :cipher_thought, :'google/thought-signature' => data_candidate_content_part[ :thoughtSignature ] } ) end if data_candidate_content_part.key?( :text ) type = data_candidate_content_part[ :thought ] ? :thought : :text if last_content.nil? || last_content[ :type ] != type contents.push( { type: type, text: data_candidate_content_part[ :text ] } ) else last_content[ :text ] = ( last_content[ :text ] || '' ) + data_candidate_content_part[ :text ] end end if function_call = data_candidate_content_part[ :functionCall ] contents.push( { type: :tool_call, tool_name: function_call[ :name ], tool_parameters: function_call[ :args ] } ) end end end choices_delta[ data_candidate_index ][ :message ][ :contents ] = contents if ( data_candidate_finish_reason && data_candidate_finish_reason.length > 1 ) end_reason = translate_finish_reason( data_candidate_finish_reason ) if end_reason == :ended && contents.any? { it&.dig( :type ) == :tool_call } end_reason = :tool_called end choices_delta[ data_candidate_index ][ :end_reason ] = end_reason end end if usage = data[ :usageMetadata ] metrics[ :input_tokens ] = usage[ :promptTokenCount ] metrics[ :output_tokens ] = usage[ :candidatesTokenCount ] end end end context[ :buffer ] = buffer context[ :metrics ] = metrics context[ :choices ] = merge_choices!( choices, choices_delta ) [ context, { choices: choices_delta } ] end def stream_result_attributes( context ) { choices: context[ :choices ], metrics: context[ :metrics ] } end alias_method :stream_result_error_attributes, :chat_result_error_attributes private def translate_finish_reason( finish_reason ) case finish_reason when 'STOP' :ended when 'MAX_TOKENS' :token_limit_exceeded when 'SAFETY', 'RECITATION', 'BLOCKLIST', 'PROHIBITED_CONTENT', 'SPII' :filtered else nil end end def translate_error_response_status( status ) case status when 400 [ :invalid_request_error, "There was an issue with the format or content of your request." ] when 403 [ :permission_error, "Your API key does not have permission to use the specified resource." ] when 404 [ :not_found_error, "The requested resource was not found." ] when 413 [ :request_too_large, "Request exceeds the maximum allowed number of bytes." ] when 422 [ :invalid_request_error, "There was an issue with the format or content of your request." ] when 429 [ :rate_limit_error, "Your account has hit a rate limit." ] when 500, 502, 503 [ :api_error, "An unexpected error has occurred internal to the providers systems." ] when 529 [ :overloaded_error, "The providers server is temporarily overloaded." ] else [ :unknown_error, " An unknown error occurred." ] end end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/utilities/deep_dup.rb
lib/intelligence/utilities/deep_dup.rb
module Intelligence module Utilities def deep_dup( object ) case object when Hash object.each_with_object( { } ) do | ( key, value ), target | target[ key ] = deep_dup( value ) end when Array object.map { | element | deep_dup( element ) } else object end end module_function :deep_dup end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapter/module_methods.rb
lib/intelligence/adapter/module_methods.rb
module Intelligence module Adapter module ModuleMethods def []( adapter_type ) raise ArgumentError.new( "An adapter type is required but nil was given." ) \ if adapter_type.nil? class_name = adapter_type.to_s.split( '_' ).map( &:capitalize ).join class_name += "::Adapter" adapter_class = Intelligence.const_get( class_name ) rescue nil if adapter_class.nil? adapter_file = File.expand_path( "../../adapters/#{adapter_type}", __FILE__ ) unless require adapter_file raise ArgumentError.new( "The Intelligence adapter file #{adapter_file} is missing or does not define #{class_name}." ) end adapter_class = Intelligence.const_get( class_name ) rescue nil end raise ArgumentError.new( "An unknown Intelligence adapter #{adapter_type} was requested." ) \ if adapter_class.nil? adapter_class end def build( adapter_type, attributes = nil, &block ) self.[]( adapter_type ).build( attributes, &block ) end def build!( adapter_type, attributes = nil, &block ) self.[]( adapter_type ).build!( attributes, &block ) end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapter/class_methods.rb
lib/intelligence/adapter/class_methods.rb
module Intelligence module Adapter module ClassMethods def build( options = nil, &block ) new( configuration: builder.build( options, &block ) ) end def build!( options = nil, &block ) new( configuration: builder.build( options, &block ) ) end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapter/instance_methods.rb
lib/intelligence/adapter/instance_methods.rb
module Intelligence module Adapter module InstanceMethods def build_options( options ) return {} unless options&.any? self.class.builder.build( options ) end def merge_options( options, other_options ) merged_options = Utilities.deep_dup( options ) other_options.each do | key, value | if merged_options[ key].is_a?( Hash ) && value.is_a?( Hash ) merged_options[ key ] = merge_options( merged_options[ key ], value ) else merged_options[ key ] = value end end merged_options end def prune_choices( choices ) choices.map do | original_choice | pruned_choice = original_choice.dup original_message = original_choice[ :message ] || { } pruned_message = original_message.dup pruned_message[ :contents ] = original_message[ :contents ]&.map do | content | { type: content[ :type ] } end pruned_choice[ :message ] = pruned_message pruned_choice end end def merge_choices!( destination, source ) source.each_with_index do | source_choice, choice_index | if destination[ choice_index ] destination_choice = destination[ choice_index ] source_message = source_choice[ :message ] || {} # merge choice keys ( everything except :message ) source_choice.each do | key, value | next if key == :message destination_choice[ key ] = value if value end destination_message = destination_choice[ :message ] ||= {} # merge message keys ( everything except :contents ) source_message.each do | key, value | next if key == :contents destination_message[ key ] = value if value end # merge the :contents arrays source_contents = Array( source_message[ :contents ] ) destination_contents = destination_message[ :contents ] ||= [] source_contents.each_with_index do | source_content, content_index | if destination_content = destination_contents[ content_index ] case destination_content[ :type ] when :thought text = destination_content[ :text ].to_s + source_content[ :text ].to_s destination_content.merge!( source_content ) destination_content[ :text ] = text when :text text = destination_content[ :text ].to_s + source_content[ :text ].to_s destination_content.merge!( source_content ) destination_content[ :text ] = text when :tool_call tool_parameters = destination_content[ :tool_parameters ].to_s + source_content[ :tool_parameters ].to_s destination_content.merge!( source_content ) destination_content[ :tool_parameters ] = tool_parameters when :web_reference # this only appears once so does not need to be merged subsequently end else # the content does not exist in the destination: duplicate the source content destination_contents[ content_index ] = Utilities.deep_dup( source_content ) end end else # choice does not exist yet in the destination: duplicate the source choice destination[ choice_index ] = Utilities.deep_dup( source_choice ) end end destination end end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
EndlessInternational/intelligence
https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/lib/intelligence/adapter/base.rb
lib/intelligence/adapter/base.rb
require_relative 'class_methods' require_relative 'instance_methods' module Intelligence module Adapter class Base include DynamicSchema::Definable extend ClassMethods def initialize( options = {}, configuration: nil ) @options = build_options( options ) @options = configuration.merge( @options ) if configuration&.any? end include InstanceMethods protected attr_reader :options end end end
ruby
MIT
2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a
2026-01-04T17:53:00.421273Z
false
eparreno/ruby_regex
https://github.com/eparreno/ruby_regex/blob/443facc47284b0e81726df46ba8543b67a94623c/test/ruby_regex_test.rb
test/ruby_regex_test.rb
require 'test/unit' require 'yaml' require File.join( File.dirname(__FILE__), '../lib/ruby_regex' ) class RubyRegexTest < Test::Unit::TestCase #Username def test_valid_usernames check_valid_regex RubyRegex::Username, ['test', 'test_test', 'test1', 'test_1'] end def test_invalid_usernames check_invalid_regex RubyRegex::Username, ['test-test', 'test.test', 'test/test', 'test@test'] end # DNI def test_valid_dnis check_valid_regex RubyRegex::Dni, ['40990889J', '99888777h'] end def test_invalid_dnis check_invalid_regex RubyRegex::Dni, ['90.900.900V', '90900900-V'] end # Email def test_valid_emails check_valid_regex RubyRegex::Email, load_fixture('emails')['valid'] end def test_invalid_emails check_invalid_regex RubyRegex::Email, load_fixture('emails')["invalid"] end # Domains def test_valid_domains check_valid_regex RubyRegex::Domain, ['test.com', 'www.test.com', 'test.es', 'www.test.es', 'test.co.uk', 'www.test.co.uk', 'test.info', 'www.test.info', 'test.com.es', 'www.test.com.es', 'test-test.com'] end def test_invalid_domains check_invalid_regex RubyRegex::Domain, ['test.', 'www.test.e', 'www.test.', 'test.e', '!test.com', 'test/test.com', 'test_test.com'] end # Url def test_valid_url check_valid_regex RubyRegex::URL, ['http://test.com', 'http://www.test.com', 'http://test.es/index', 'http://www.test.es/index.html', 'https://test.co.uk', 'http://www.test.co.uk/index.html?id=34&name=username'] end def test_invalid_url check_invalid_regex RubyRegex::URL, ['test.com', 'www.test.com', 'http://test.es-index', 'http://www.test.es?index.html'] end # CreditCard def test_valid_credit_cards check_valid_regex RubyRegex::CreditCard, [ '1234123412341234', '1234 1234 1234 1234', '1234-1234-1234-1234'] end def test_invalid_credit_cards check_invalid_regex RubyRegex::CreditCard, ['1234_1234_1234_1234', '1234', '12341234', '123412341234', '1234 1234 1234 1234', '1234-1234 12341234', '123a-1234-1234-1234'] end # US Social Security def test_valid_usss_numbers check_valid_regex RubyRegex::USSocialSecurity, ['123-12-1234'] end def test_invalid_usss_numbers check_invalid_regex RubyRegex::USSocialSecurity, [ '1234_1234_1234_1234', '1234', '123121234', '123_12_1234', '123 12 1234'] end # General Postal Code def test_valid_postal_codes check_valid_regex RubyRegex::GeneralPostalCode, ['12345'] end def test_invalid_postal_codes check_invalid_regex RubyRegex::GeneralPostalCode, [ '1', '12', '123', '1234', '123456'] end # ZIP Code def test_valid_zip_codes check_valid_regex RubyRegex::ZIPCode, [ '12345', '12345-1234'] end def test_invalid_zip_codes check_invalid_regex RubyRegex::ZIPCode, [ '1', '12', '123', '1234', '123456', '12345_1234', '12345 1234', '1234-1234'] end # Twitter usernames def test_valid_twitter_usernames check_valid_regex RubyRegex::TwitterUsername, ['ji', 'nickel84', 'sepa_rate'] end def test_invalid_twitter_usernames check_invalid_regex RubyRegex::TwitterUsername, ['nickel 83', 'h.ppywebcoder'] end # Github usernames def test_valid_github_usernames check_valid_regex RubyRegex::GithubUsername, ['ji', 'nickel84', 'sepa_rate', 'ernesto-jimenez'] end def test_invalid_github_usernames check_invalid_regex RubyRegex::GithubUsername, ['nickel 84', 'h.ppywebcoder'] end # Slideshare usernames def test_valid_slideshare_usernames check_valid_regex RubyRegex::SlideshareUsername, ['ji', 'nickel84'] end def test_invalid_slideshare_usernames check_invalid_regex RubyRegex::SlideshareUsername, ['nickel 84', 'h.ppywebcoder', 'sepa_rate', 'ernesto-jimenez'] end # Del.icio.us usernames def test_valid_delicious_usernames check_valid_regex RubyRegex::DeliciousUsername, ['ji', 'nickel84', 'sepa_rate', 'ernesto-jimenez'] end def test_invalid_delicious_usernames check_invalid_regex RubyRegex::DeliciousUsername, ['nickel 84', 'h.ppywebcoder'] end def test_valid_uuids check_valid_regex RubyRegex::UUID, ['550e8400e29b41d4a716446655440000', '550e8400-e29b-41d4-a716-446655440000', '6ba7b8109dad11d180b400c04fd430c8', '6ba7b810-9dad-11d1-80b4-00c04fd430c8'] end def test_invalid_uuids check_invalid_regex RubyRegex::UUID, ['6ba7b810-9dad-11d180b400c04fd430c8', 'zba7b810-9dad-11d1-80b4-00c04fd430c8', '6ba7b81-9ad-1d1-0b4-00c04fd430c8', '1234', 'asdf', '555-555-5555', 'abcd@qwerty.com'] end # DBDate def test_valid_db_dates check_valid_regex RubyRegex::DBDate, load_fixture('db_dates')['valid'] end def test_invalid_db_dates check_invalid_regex RubyRegex::DBDate, load_fixture('db_dates')['invalid'] end # DBDateTime def test_valid_db_date_times check_valid_regex RubyRegex::DBDateTime, load_fixture('db_date_times')['valid'] end def test_invalid_db_date_times check_invalid_regex RubyRegex::DBDateTime, load_fixture('db_date_times')['invalid'] end # SpanishBankAccountNumber def test_valid_spanish_bank_account_numbers check_valid_regex RubyRegex::SpanishBankAccountNumber, load_fixture('spanish_bank_account_numbers')['valid'] end def test_invalid_spanish_bank_account_numbers check_invalid_regex RubyRegex::SpanishBankAccountNumber, load_fixture('spanish_bank_account_numbers')['invalid'] end # IBAN def test_valid_iban check_valid_regex RubyRegex::IBAN, load_fixture('ibans')['valid'] end def test_invalid_iban check_invalid_regex RubyRegex::IBAN, load_fixture('ibans')['invalid'] end # MacAddress def test_valid_mac_addresses check_valid_regex RubyRegex::MacAddress, load_fixture('mac_addresses')['valid'] end def test_invalid_mac_addresses check_invalid_regex RubyRegex::SpanishBankAccountNumber, load_fixture('mac_addresses')['invalid'] end private def load_fixture( name ) YAML.load( File.read( File.join( File.dirname(__FILE__), 'fixtures', "#{name}.yml" ) ) ) end def check_valid_regex(regexp, strings) strings.each do |str| message = build_message(message, '<?> should be valid but it is not', str) assert(str =~ regexp, message) end end def check_invalid_regex(regexp, strings) strings.each do |str| message = build_message(message, '<?> should be invalid but it is not', str) assert(str !~ regexp, message) end end end
ruby
MIT
443facc47284b0e81726df46ba8543b67a94623c
2026-01-04T17:55:37.482157Z
false
eparreno/ruby_regex
https://github.com/eparreno/ruby_regex/blob/443facc47284b0e81726df46ba8543b67a94623c/lib/ruby_regex.rb
lib/ruby_regex.rb
module RubyRegex # Username # This regular expression doesn't validate username's length Username = /\A[a-zA-Z0-9_]*\z/ # Dni (spanish ID card) Dni = /\A\d{8}[A-Za-z]{1}\z/ # URL Url = URL = /(\A\z)|(\A(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\z)/ix # Domain Domain = /(\A\z)|(\A[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?)?\z)/ix # CreditCard # Validates Credit Card numbers, Checks if it contains 16 numbers in groups of 4 separated by -, space or nothing CreditCard = /\A(\d{4}-){3}\d{4}\z|\A(\d{4}\s){3}\d{4}\z|\A\d{16}\z/ # MasterCard credit card MasterCard = /\A5[1-5]\d{14}\z/ # Visa credit card Visa = /\A4\d{15}\z/ # US Social Security USSocialSecurity = /\A\d{3}-\d{2}-\d{4}\z/ # General postal code # Validates a 5 digits postal code GeneralPostalCode = /\A\d{5}\z/ # US ZIP code # Validates US ZIP Code (basic and extended format) ZIPCode = /\A(\d{5}\z)|(\d{5}-\d{4}\z)/ # Twitter username TwitterUsername = /\A([a-z0-9\_])+\z/ix # Github username GithubUsername = /\A([a-z0-9\_\-])+\z/ix # Slideshare username SlideshareUsername = /\A([a-z0-9])+\z/ix # Del.icio.us username DeliciousUsername = /\A([a-z0-9\_\-])+\z/ix # Email # From the email regex research: http://fightingforalostcause.net/misc/2006/compare-email-regex.php # Authors: James Watts and Francisco Jose Martin Moreno Email = /\A([\w\!\#\z\%\&\'\*\+\-\/\=\?\\A\`{\|\}\~]+\.)*[\w\+-]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)\z/i # UUID # Validates a UUID as defined: http://en.wikipedia.org/wiki/Universally_unique_identifier UUID = /\A(\h{32}|\h{8}-\h{4}-\h{4}-\h{4}-\h{12})\z/ # Date DB format YYYY-MM-DD # I know it will validate 2001-02-31 but is I think we are focusing in formats more than in parsing DBDate = /\A\d{4}-(#{("01".."12").to_a.join("|")})-(#{("01".."31").to_a.join("|")})\z/ # Date Time DB format YYYY-MM-DD hh:mm:ss DBDateTime = /\A\d{4}-(#{("01".."12").to_a.join("|")})-(#{("01".."31").to_a.join("|")})\s(#{("00".."23").to_a.join("|")}):(#{("00".."59").to_a.join("|")}):(#{("00".."59").to_a.join("|")})\z/ # SpanishBankAccountNumber SpanishBankAccountNumber = /\A\d{4}[ -]?\d{4}[ -]?\d{2}[ -]?\d{10}\z/ # IBAN # Source: http://snipplr.com/view/15322/iban-regex-all-ibans/ # You have to remove spaces or any separator character from the original field before use this regex IBAN = /[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}/ # MacAddress MacAddress = /\A([0-9A-F]{2}[:-]){5}([0-9A-F]{2})\z/i end
ruby
MIT
443facc47284b0e81726df46ba8543b67a94623c
2026-01-04T17:55:37.482157Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true require 'rubygems' require 'minitest/autorun' require 'active_record' require 'mongoid' # Configure Rails Environment environment = ENV['RAILS_ENV'] = 'test' rails_root = File.expand_path('dummy', __dir__) database_yml = File.expand_path('config/database.yml', rails_root) ActiveRecord::Base.configurations = YAML.load_file(database_yml) config = ActiveRecord::Base.configurations[environment] db = File.expand_path(config['database'], rails_root) # Drop the test database and migrate up FileUtils.rm(db) if File.exist?(db) ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: db) ActiveRecord::Base.connection ActiveRecord::Migration.verbose = false ActiveRecord::Migrator.up File.expand_path('db/migrate', rails_root) # Load mongoid config Mongoid.load!(File.expand_path('config/mongoid3.yml', rails_root), :test) Mongoid.logger.level = :info # Load dummy rails app require File.expand_path('config/environment.rb', rails_root) Rails.backtrace_cleaner.remove_silencers! # Load support files (reloadable reloads canard) Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/support/reloadable.rb
test/support/reloadable.rb
# frozen_string_literal: true module MiniTest class Unit class TestCase def teardown Object.send(:remove_const, 'Canard') if Object.const_defined?('Canard') GC.start end def setup ['canard/abilities.rb', 'canard/user_model.rb', 'canard/find_abilities.rb'].each do |file| file_path = File.join(File.expand_path('../../lib', __dir__), file) load file_path end end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/abilities/administrators.rb
test/abilities/administrators.rb
# frozen_string_literal: true Canard::Abilities.for(:administrator) do can :manage, [Activity, User] end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/abilities/users.rb
test/dummy/app/abilities/users.rb
# frozen_string_literal: true Canard::Abilities.for(:user) do can %i[edit update], Member, user_id: user.id end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/abilities/editors.rb
test/dummy/app/abilities/editors.rb
# frozen_string_literal: true Canard::Abilities.for(:editor) do includes_abilities_of :author cannot :create, Post end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/abilities/admins.rb
test/dummy/app/abilities/admins.rb
# frozen_string_literal: true Canard::Abilities.for(:admin) do can :manage, [Post, User] cannot :destroy, User do |u| (user == u) end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/abilities/authors.rb
test/dummy/app/abilities/authors.rb
# frozen_string_literal: true Canard::Abilities.for(:author) do can %i[create update read], Post end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/abilities/guests.rb
test/dummy/app/abilities/guests.rb
# frozen_string_literal: true Canard::Abilities.for(:guest) do can :read, Post end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/controllers/application_controller.rb
test/dummy/app/controllers/application_controller.rb
# frozen_string_literal: true class ApplicationController < ActionController::Base protect_from_forgery end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/plain_ruby_user.rb
test/dummy/app/models/plain_ruby_user.rb
# frozen_string_literal: true class PlainRubyUser extend Canard::UserModel attr_accessor :roles_mask def initialize(*roles) self.roles = roles end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/member.rb
test/dummy/app/models/member.rb
# frozen_string_literal: true class Member < ActiveRecord::Base belongs_to :user attr_accessible :user, :user_id end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/plain_ruby_non_user.rb
test/dummy/app/models/plain_ruby_non_user.rb
# frozen_string_literal: true class PlainRubyNonUser extend Canard::UserModel end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/post.rb
test/dummy/app/models/post.rb
# frozen_string_literal: true class Post < ActiveRecord::Base end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/activity.rb
test/dummy/app/models/activity.rb
# frozen_string_literal: true class Activity end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/mongoid_user.rb
test/dummy/app/models/mongoid_user.rb
# frozen_string_literal: true class MongoidUser include Mongoid::Document acts_as_user roles: %i[viewer author admin] end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/user_without_role.rb
test/dummy/app/models/user_without_role.rb
# frozen_string_literal: true class UserWithoutRole < ActiveRecord::Base acts_as_user attr_accessible :roles end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/user_without_role_mask.rb
test/dummy/app/models/user_without_role_mask.rb
# frozen_string_literal: true class UserWithoutRoleMask < ActiveRecord::Base attr_accessible :roles end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/app/models/user.rb
test/dummy/app/models/user.rb
# frozen_string_literal: true class User < ActiveRecord::Base acts_as_user roles: %i[viewer author admin editor] attr_accessible :roles end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/db/schema.rb
test/dummy/db/schema.rb
# frozen_string_literal: true # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(version: 20_120_430_083_231) do create_table 'members', force: true do |t| t.integer 'user_id' end create_table 'user_without_role_masks', force: true do |t| t.integer 'my_roles_mask' end create_table 'user_without_roles', force: true do |t| t.integer 'roles_mask' end create_table 'users', force: true do |t| t.integer 'roles_mask' end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/db/migrate/20120430083231_initialize_db.rb
test/dummy/db/migrate/20120430083231_initialize_db.rb
# frozen_string_literal: true class InitializeDb < ActiveRecord::Migration def change create_table :users, force: true do |t| t.integer :roles_mask end create_table :user_without_roles, force: true do |t| t.integer :roles_mask end create_table :user_without_role_masks, force: true do |t| t.integer :my_roles_mask end create_table :members, force: true do |t| t.references :user end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/application.rb
test/dummy/config/application.rb
# frozen_string_literal: true require File.expand_path('boot', __dir__) # Pick the frameworks you want: require 'active_record/railtie' require 'action_controller/railtie' require 'active_resource/railtie' require 'rails/test_unit/railtie' Bundler.require if defined?(Bundler) require 'canard' module Dummy class Application < Rails::Application # Configure the default encoding used in templates for Ruby 1.9. config.encoding = 'utf-8' # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enforce whitelist mode for mass assignment. # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. config.active_record.whitelist_attributes = true end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/environment.rb
test/dummy/config/environment.rb
# frozen_string_literal: true # Load the rails application require File.expand_path('application', __dir__) # Initialize the rails application Dummy::Application.initialize!
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/routes.rb
test/dummy/config/routes.rb
# frozen_string_literal: true Dummy::Application.routes.draw do end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/boot.rb
test/dummy/config/boot.rb
# frozen_string_literal: true require 'rubygems' gemfile = File.expand_path('../../../Gemfile', __dir__) if File.exist?(gemfile) ENV['BUNDLE_GEMFILE'] = gemfile require 'bundler' Bundler.setup end $LOAD_PATH.unshift File.expand_path('../../../lib', __dir__)
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/initializers/session_store.rb
test/dummy/config/initializers/session_store.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Dummy::Application.config.session_store :active_record_store
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/initializers/wrap_parameters.rb
test/dummy/config/initializers/wrap_parameters.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do self.include_root_in_json = false end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/initializers/secret_token.rb
test/dummy/config/initializers/secret_token.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Dummy::Application.config.secret_token = 'c2af159f67aa6955b415217bf5aa58779dec6fccc201c7bf38f9a8ad25893d88596778df8bb7106153666f41c3161cfb7f89b639a2c15a084abb6c2c57f74c55'
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/environments/test.rb
test/dummy/config/environments/test.rb
# frozen_string_literal: true Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = 'public, max-age=3600' # Log error messages when you accidentally call methods on nil config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict # Print deprecation notices to the stderr config.active_support.deprecation = :stderr end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/dummy/config/environments/development.rb
test/dummy/config/environments/development.rb
# frozen_string_literal: true Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) config.active_record.auto_explain_threshold_in_seconds = 0.5 # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/canard/find_abilities_test.rb
test/canard/find_abilities_test.rb
# frozen_string_literal: true require 'test_helper' describe Canard do describe 'find_abilities' do before do Canard::Abilities.definition_paths = [File.expand_path('../dummy/app/abilities', __dir__)] end it 'loads the abilities into ability_definitions' do Canard.find_abilities Canard.ability_definitions.keys.must_include :admin end it 'finds abilities in the default path' do Canard.find_abilities Canard.ability_definitions.keys.must_include :author Canard.ability_definitions.keys.wont_include :administrator end it 'finds abilities in additional paths' do Canard::Abilities.definition_paths << File.expand_path('../abilities', __dir__) Canard.find_abilities Canard.ability_definitions.keys.must_include :author Canard.ability_definitions.keys.must_include :administrator end it 'reloads existing abilities' do Canard.find_abilities Canard::Abilities.send(:instance_variable_set, '@definitions', {}) Canard.find_abilities Canard.ability_definitions.keys.must_include :author Canard.ability_definitions.keys.must_include :admin end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/canard/abilities_test.rb
test/canard/abilities_test.rb
# frozen_string_literal: true require 'test_helper' require 'canard' describe 'Canard::Abilities' do subject { Canard::Abilities } describe 'ability_paths' do it 'defaults to app/abilities' do subject.definition_paths.must_include 'app/abilities' end it 'appends paths' do subject.definition_paths << 'other_abilities' subject.definition_paths.must_include 'other_abilities' end it 'can be overwritten' do subject.definition_paths = ['other_abilities'] subject.definition_paths.must_equal ['other_abilities'] end end describe 'default_path' do it 'defaults to app/abilities' do subject.default_path.must_equal 'app/abilities' end it 'can be changhed' do subject.default_path = 'other_abilities' subject.default_path.must_equal 'other_abilities' end end describe 'for' do it 'adds the block to the definitions' do block = -> { puts 'some block' } subject.for(:definition, &block) assert_equal block, subject.definitions[:definition] end it 'normalises the key to a symbol' do subject.for('definition') { puts 'a block' } subject.definitions.keys.must_include :definition end it 'rasises ArgumentError if no block is provided' do proc { subject.for(:definition) }.must_raise ArgumentError end it 'creates a lowercaae key' do subject.for('NotCamelCase') { puts 'a block' } subject.definitions.keys.must_include :not_camel_case end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/canard/ability_test.rb
test/canard/ability_test.rb
# frozen_string_literal: true require 'test_helper' describe Ability do before do Canard::Abilities.definition_paths = [File.expand_path('../dummy/app/abilities', __dir__)] # reload abilities because the reloader will have removed them after the railtie ran Canard.find_abilities end describe 'new' do describe 'with a user' do let(:user) { User.new } subject { Ability.new(user) } it 'assign the user to Ability#user' do subject.user.must_equal user end end describe 'with a model that references a user' do let(:user) { User.create } let(:member) { Member.new(user: user) } subject { Ability.new(member) } it 'assign the user to Ability#user' do subject.user.must_equal user end end describe 'with a user that has author role' do let(:user) { User.create(roles: [:author]) } let(:member) { Member.create(user: user) } let(:other_member) { Member.new(user: User.create) } subject { Ability.new(user) } it 'has all the abilities of the base class' do subject.can?(:edit, member).must_equal true subject.can?(:update, member).must_equal true subject.can?(:edit, other_member).wont_equal true subject.can?(:update, other_member).wont_equal true end it 'has all the abilities of an author' do subject.can?(:new, Post).must_equal true subject.can?(:create, Post).must_equal true subject.can?(:edit, Post).must_equal true subject.can?(:update, Post).must_equal true subject.can?(:show, Post).must_equal true subject.can?(:index, Post).must_equal true end it 'has no admin abilities' do subject.cannot?(:destroy, Post).must_equal true end end describe 'with a user that has admin and author roles' do let(:user) { User.create(roles: %i[author admin]) } let(:member) { Member.create(user: user) } let(:other_user) { User.create } let(:other_member) { Member.new(user: other_user) } subject { Ability.new(user) } it 'has all the abilities of the base class' do subject.can?(:edit, member).must_equal true subject.can?(:update, member).must_equal true subject.cannot?(:edit, other_member).must_equal true subject.cannot?(:update, other_member).must_equal true end it 'has all the abilities of an author' do subject.can?(:new, Post).must_equal true end it 'has the abilities of an admin' do subject.can?(:manage, Post).must_equal true subject.can?(:manage, other_user).must_equal true subject.can?(:destroy, other_user).must_equal true subject.cannot?(:destroy, user).must_equal true end end describe 'a user with editor role' do let(:user) { User.create(roles: [:editor]) } let(:member) { Member.create(user: user) } let(:other_user) { User.create } let(:other_member) { Member.new(user: other_user) } subject { Ability.new(user) } it 'has all the abilities of the base class' do subject.can?(:edit, member).must_equal true subject.can?(:update, member).must_equal true subject.cannot?(:edit, other_member).must_equal true subject.cannot?(:update, other_member).must_equal true end it "has most of the abilities of authors, except it can't create Posts" do subject.can?(:update, Post).must_equal true subject.can?(:read, Post).must_equal true subject.cannot?(:create, Post).must_equal true end end describe 'with no user' do subject { Ability.new } it 'applies the guest abilities' do subject.can?(:index, Post) subject.can?(:show, Post) subject.cannot?(:create, Post) subject.cannot?(:update, Post) subject.cannot?(:destroy, Post) subject.cannot?(:show, User) subject.cannot?(:show, Member) end end describe 'with an instance of an anonymous class that has author role' do let(:klass) do Class.new do extend Canard::UserModel attr_accessor :roles_mask acts_as_user roles: %i[author admin] def initialize(*roles) self.roles = roles end end end let(:instance) { klass.new(:author) } describe 'for base class abilities' do it 'does nothing' do proc { Ability.new(instance) }.must_be_silent end end describe 'for assigned roles' do subject { Ability.new(instance) } it 'has all the abilities of an author' do subject.can?(:new, Post).must_equal true subject.can?(:create, Post).must_equal true subject.can?(:edit, Post).must_equal true subject.can?(:update, Post).must_equal true subject.can?(:show, Post).must_equal true subject.can?(:index, Post).must_equal true end it 'has no admin abilities' do subject.cannot?(:destroy, Post).must_equal true end end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/canard/canard_test.rb
test/canard/canard_test.rb
# frozen_string_literal: true require 'test_helper' require 'canard' describe Canard do describe 'ability_definitions' do it 'should be an accessor' do Canard.must_respond_to(:ability_definitions) end it 'should be a hash' do Canard.ability_definitions.must_be_instance_of Hash end end describe 'ability_key' do it 'returns a snake case version of the string' do class_name = 'CamelCaseString' key = :camel_case_string Canard.ability_key(class_name).must_equal key end it 'prepends namespaces to the class name' do class_name = 'Namespace::CamelCaseString' key = :namespace_camel_case_string Canard.ability_key(class_name).must_equal key end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/canard/user_model_test.rb
test/canard/user_model_test.rb
# frozen_string_literal: true require 'test_helper' describe Canard::UserModel do describe 'acts_as_user' do describe 'integrating RoleModel' do before do PlainRubyUser.acts_as_user end it 'adds role_model to the class' do PlainRubyUser.included_modules.must_include RoleModel PlainRubyUser.new.must_respond_to :roles end end describe 'with a roles_mask' do describe 'and :roles => [] specified' do before do PlainRubyUser.acts_as_user roles: %i[viewer author admin] end it 'sets the valid_roles for the class' do PlainRubyUser.valid_roles.must_equal %i[viewer author admin] end end describe 'and no :roles => [] specified' do before do PlainRubyUser.acts_as_user end it 'sets no roles' do PlainRubyUser.valid_roles.must_equal [] end end end describe 'with no roles_mask' do before do PlainRubyNonUser.acts_as_user roles: %i[viewer author admin] end it 'sets no roles' do PlainRubyNonUser.valid_roles.must_equal [] end end describe 'setting the role_mask' do before do PlainRubyNonUser.send :attr_accessor, :my_roles PlainRubyNonUser.acts_as_user roles: %i[viewer author], roles_mask: :my_roles end it 'sets the valid_roles for the class' do PlainRubyNonUser.valid_roles.must_equal %i[viewer author] end end end describe 'scopes' do before do PlainRubyUser.acts_as_user roles: %i[viewer author admin] end describe 'on a plain Ruby class' do subject { PlainRubyUser } it 'creates no scope methods' do subject.wont_respond_to :admins subject.wont_respond_to :authors subject.wont_respond_to :viewers subject.wont_respond_to :non_admins subject.wont_respond_to :non_authors subject.wont_respond_to :non_viewers subject.wont_respond_to :with_any_role subject.wont_respond_to :with_all_roles end end end end describe Canard::UserModel::InstanceMethods do before do Canard::Abilities.default_path = File.expand_path('../dummy/app/abilities', __dir__) # reload abilities because the reloader will have removed them after the railtie ran Canard.find_abilities end describe 'ability' do before do PlainRubyUser.acts_as_user roles: %i[admin author] end subject { PlainRubyUser.new(:author).ability } it 'returns an ability for this instance' do subject.must_be_instance_of Ability end it 'has the users abilities' do subject.can?(:new, Post).must_equal true subject.can?(:create, Post).must_equal true subject.can?(:edit, Post).must_equal true subject.can?(:update, Post).must_equal true subject.can?(:show, Post).must_equal true subject.can?(:index, Post).must_equal true end it 'has no other abilities' do subject.cannot?(:destroy, Post).must_equal true end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/canard/adapters/active_record_test.rb
test/canard/adapters/active_record_test.rb
# frozen_string_literal: true require 'test_helper' describe Canard::Adapters::ActiveRecord do describe 'acts_as_user' do describe 'with a role_mask' do describe 'and :roles => [] specified' do it 'sets the valid_roles for the class' do User.valid_roles.must_equal %i[viewer author admin editor] end end describe 'and no :roles => [] specified' do it 'sets no roles' do UserWithoutRole.valid_roles.must_equal [] end end end describe 'with no roles_mask' do before do UserWithoutRoleMask.acts_as_user roles: %i[viewer admin] end it 'sets no roles' do UserWithoutRoleMask.valid_roles.must_equal [] end end describe 'with no table' do subject { Class.new(ActiveRecord::Base) } it 'sets no roles' do subject.class_eval { acts_as_user roles: [:admin] } subject.valid_roles.must_equal [] end it 'does not raise any errors' do proc { subject.class_eval { acts_as_user roles: [:admin] } }.must_be_silent end it 'returns nil' do subject.class_eval { acts_as_user roles: [:admin] }.must_be_nil end end describe 'with an alternative roles_mask specified' do before do UserWithoutRoleMask.acts_as_user roles_mask: :my_roles_mask, roles: %i[viewer admin] end it 'sets no roles' do UserWithoutRoleMask.valid_roles.must_equal %i[viewer admin] end end end describe 'scopes' do describe 'on an ActiveRecord model with roles' do before do @no_role = User.create @admin_author_viewer = User.create(roles: %i[admin author viewer]) @author_viewer = User.create(roles: %i[author viewer]) @viewer = User.create(roles: [:viewer]) @admin_only = User.create(roles: [:admin]) @author_only = User.create(roles: [:author]) end after do User.delete_all end subject { User } it 'adds a scope to return instances with each role' do subject.must_respond_to :admins subject.must_respond_to :authors subject.must_respond_to :viewers end it 'adds a scope to return instances without each role' do subject.must_respond_to :non_admins subject.must_respond_to :non_authors subject.must_respond_to :non_viewers end describe 'finding instances with a role' do describe 'admins scope' do subject { User.admins.sort_by(&:id) } it 'returns only admins' do subject.must_equal [@admin_author_viewer, @admin_only].sort_by(&:id) end it "doesn't return non admins" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @viewer end end describe 'authors scope' do subject { User.authors.sort_by(&:id) } it 'returns only authors' do subject.must_equal [@admin_author_viewer, @author_viewer, @author_only].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @viewer end end describe 'viewers scope' do subject { User.viewers.sort_by(&:id) } it 'returns only viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @viewer].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @author_only end end end describe 'finding instances without a role' do describe 'non_admins scope' do subject { User.non_admins.sort_by(&:id) } it 'returns only non_admins' do subject.must_equal [@no_role, @author_viewer, @viewer, @author_only].sort_by(&:id) end it "doesn't return admins" do subject.wont_include @admin_author_viewer subject.wont_include @admin_only end end describe 'non_authors scope' do subject { User.non_authors.sort_by(&:id) } it 'returns only non_authors' do subject.must_equal [@no_role, @viewer, @admin_only].sort_by(&:id) end it "doesn't return authors" do subject.wont_include @admin_author_viewer subject.wont_include @author_viewer subject.wont_include @author_only end end describe 'non_viewers scope' do subject { User.non_viewers.sort_by(&:id) } it 'returns only non_viewers' do subject.must_equal [@no_role, @admin_only, @author_only].sort_by(&:id) end it "doesn't return viewers" do subject.wont_include @admin_author_viewer subject.wont_include @author_viewer subject.wont_include @viewer end end end describe 'with_any_role' do describe 'specifying admin only' do subject { User.with_any_role(:admin).sort_by(&:id) } it 'returns only admins' do subject.must_equal [@admin_author_viewer, @admin_only].sort_by(&:id) end it "doesn't return non admins" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @viewer end end describe 'specifying author only' do subject { User.with_any_role(:author).sort_by(&:id) } it 'returns only authors' do subject.must_equal [@admin_author_viewer, @author_viewer, @author_only].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @viewer end end describe 'specifying viewer only' do subject { User.with_any_role(:viewer).sort_by(&:id) } it 'returns only viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @viewer].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @author_only end end describe 'specifying admin and author' do subject { User.with_any_role(:admin, :author).sort_by(&:id) } it 'returns only admins and authors' do subject.must_equal [@admin_author_viewer, @author_viewer, @admin_only, @author_only].sort_by(&:id) end it "doesn't return non admins or authors" do subject.wont_include @no_role subject.wont_include @viewer end end describe 'specifying admin and viewer' do subject { User.with_any_role(:admin, :viewer).sort_by(&:id) } it 'returns only admins and viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @admin_only, @viewer].sort_by(&:id) end it "doesn't return non admins or viewers" do subject.wont_include @no_role subject.wont_include @author_only end end describe 'specifying author and viewer' do subject { User.with_any_role(:author, :viewer).sort_by(&:id) } it 'returns only authors and viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @author_only, @viewer].sort_by(&:id) end it "doesn't return non authors or viewers" do subject.wont_include @no_role subject.wont_include @admin_only end end describe 'specifying admin, author and viewer' do subject { User.with_any_role(:admin, :author, :viewer).sort_by(&:id) } it 'returns only admins, authors and viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @admin_only, @author_only, @viewer].sort_by(&:id) end it "doesn't return non admins, authors or viewers" do subject.wont_include @no_role end end end describe 'with_all_roles' do describe 'specifying admin only' do subject { User.with_all_roles(:admin).sort_by(&:id) } it 'returns only admins' do subject.must_equal [@admin_author_viewer, @admin_only].sort_by(&:id) end it "doesn't return non admins" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @viewer end end describe 'specifying author only' do subject { User.with_all_roles(:author).sort_by(&:id) } it 'returns only authors' do subject.must_equal [@admin_author_viewer, @author_viewer, @author_only].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @viewer end end describe 'specifying viewer only' do subject { User.with_all_roles(:viewer).sort_by(&:id) } it 'returns only viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @viewer].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @author_only end end describe 'specifying admin and author' do subject { User.with_all_roles(:admin, :author).sort_by(&:id) } it 'returns only admins and authors' do subject.must_equal [@admin_author_viewer].sort_by(&:id) end it "doesn't return non admin and authors" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @admin_only subject.wont_include @viewer end end describe 'specifying admin and viewer' do subject { User.with_all_roles(:admin, :viewer).sort_by(&:id) } it 'returns only admins and viewers' do subject.must_equal [@admin_author_viewer].sort_by(&:id) end it "doesn't return non admins or viewers" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @admin_only subject.wont_include @viewer end end describe 'specifying author and viewer' do subject { User.with_all_roles(:author, :viewer).sort_by(&:id) } it 'returns only authors and viewers' do subject.must_equal [@admin_author_viewer, @author_viewer].sort_by(&:id) end it "doesn't return non authors or viewers" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @author_only subject.wont_include @viewer end end describe 'specifying admin, author and viewer' do subject { User.with_all_roles(:admin, :author, :viewer).sort_by(&:id) } it 'returns only admins, authors and viewers' do subject.must_equal [@admin_author_viewer].sort_by(&:id) end it "doesn't return non admins, authors or viewers" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @admin_only subject.wont_include @viewer end end end describe 'with_only_roles' do describe 'specifying one role' do subject { User.with_only_roles(:admin).sort_by(&:id) } it 'returns users with just that role' do subject.must_equal [@admin_only].sort_by(&:id) end it "doesn't return any other users" do subject.wont_include @no_role subject.wont_include @admin_author_viewer subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @viewer end end describe 'specifying multiple roles' do subject { User.with_only_roles(:author, :viewer).sort_by(&:id) } it 'returns only users with no more or less roles' do subject.must_equal [@author_viewer].sort_by(&:id) end it "doesn't return any other users" do subject.wont_include @no_role subject.wont_include @admin_author_viewer subject.wont_include @admin_only subject.wont_include @author_only subject.wont_include @viewer end end end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/test/canard/adapters/mongoid_test.rb
test/canard/adapters/mongoid_test.rb
# frozen_string_literal: true require 'test_helper' require 'bson' describe Canard::Adapters::Mongoid do describe 'acts_as_user' do describe 'with a role_mask' do describe 'and :roles => [] specified' do it 'sets the valid_roles for the class' do MongoidUser.valid_roles.must_equal %i[viewer author admin] end end end end describe 'scopes' do describe 'on an Mongoid model with roles' do before do @no_role = MongoidUser.create @admin_author_viewer = MongoidUser.create(roles: %i[admin author viewer]) @author_viewer = MongoidUser.create(roles: %i[author viewer]) @viewer = MongoidUser.create(roles: [:viewer]) @admin_only = MongoidUser.create(roles: [:admin]) @author_only = MongoidUser.create(roles: [:author]) end after do MongoidUser.delete_all end subject { MongoidUser } it 'adds a scope to return instances with each role' do subject.must_respond_to :admins subject.must_respond_to :authors subject.must_respond_to :viewers end it 'adds a scope to return instances without each role' do subject.must_respond_to :non_admins subject.must_respond_to :non_authors subject.must_respond_to :non_viewers end describe 'finding instances with a role' do describe 'admins scope' do subject { MongoidUser.admins.sort_by(&:id) } it 'returns only admins' do subject.must_equal [@admin_author_viewer, @admin_only].sort_by(&:id) end it "doesn't return non admins" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @viewer end end describe 'authors scope' do subject { MongoidUser.authors.sort_by(&:id) } it 'returns only authors' do subject.must_equal [@admin_author_viewer, @author_viewer, @author_only].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @viewer end end describe 'viewers scope' do subject { MongoidUser.viewers.sort_by(&:id) } it 'returns only viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @viewer].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @author_only end end end describe 'finding instances without a role' do describe 'non_admins scope' do subject { MongoidUser.non_admins.sort_by(&:id) } it 'returns only non_admins' do subject.must_equal [@no_role, @author_viewer, @viewer, @author_only].sort_by(&:id) end it "doesn't return admins" do subject.wont_include @admin_author_viewer subject.wont_include @admin_only end end describe 'non_authors scope' do subject { MongoidUser.non_authors.sort_by(&:id) } it 'returns only non_authors' do subject.must_equal [@no_role, @viewer, @admin_only].sort_by(&:id) end it "doesn't return authors" do subject.wont_include @admin_author_viewer subject.wont_include @author_viewer subject.wont_include @author_only end end describe 'non_viewers scope' do subject { MongoidUser.non_viewers.sort_by(&:id) } it 'returns only non_viewers' do subject.must_equal [@no_role, @admin_only, @author_only].sort_by(&:id) end it "doesn't return viewers" do subject.wont_include @admin_author_viewer subject.wont_include @author_viewer subject.wont_include @viewer end end end describe 'with_any_role' do describe 'specifying admin only' do subject { MongoidUser.with_any_role(:admin).sort_by(&:id) } it 'returns only admins' do subject.must_equal [@admin_author_viewer, @admin_only].sort_by(&:id) end it "doesn't return non admins" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @viewer end end describe 'specifying author only' do subject { MongoidUser.with_any_role(:author).sort_by(&:id) } it 'returns only authors' do subject.must_equal [@admin_author_viewer, @author_viewer, @author_only].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @viewer end end describe 'specifying viewer only' do subject { MongoidUser.with_any_role(:viewer).sort_by(&:id) } it 'returns only viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @viewer].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @author_only end end describe 'specifying admin and author' do subject { MongoidUser.with_any_role(:admin, :author).sort_by(&:id) } it 'returns only admins and authors' do subject.must_equal [@admin_author_viewer, @author_viewer, @admin_only, @author_only].sort_by(&:id) end it "doesn't return non admins or authors" do subject.wont_include @no_role subject.wont_include @viewer end end describe 'specifying admin and viewer' do subject { MongoidUser.with_any_role(:admin, :viewer).sort_by(&:id) } it 'returns only admins and viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @admin_only, @viewer].sort_by(&:id) end it "doesn't return non admins or viewers" do subject.wont_include @no_role subject.wont_include @author_only end end describe 'specifying author and viewer' do subject { MongoidUser.with_any_role(:author, :viewer).sort_by(&:id) } it 'returns only authors and viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @author_only, @viewer].sort_by(&:id) end it "doesn't return non authors or viewers" do subject.wont_include @no_role subject.wont_include @admin_only end end describe 'specifying admin, author and viewer' do subject { MongoidUser.with_any_role(:admin, :author, :viewer).sort_by(&:id) } it 'returns only admins, authors and viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @admin_only, @author_only, @viewer].sort_by(&:id) end it "doesn't return non admins, authors or viewers" do subject.wont_include @no_role end end end describe 'with_all_roles' do describe 'specifying admin only' do subject { MongoidUser.with_all_roles(:admin).sort_by(&:id) } it 'returns only admins' do subject.must_equal [@admin_author_viewer, @admin_only].sort_by(&:id) end it "doesn't return non admins" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @viewer end end describe 'specifying author only' do subject { MongoidUser.with_all_roles(:author).sort_by(&:id) } it 'returns only authors' do subject.must_equal [@admin_author_viewer, @author_viewer, @author_only].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @viewer end end describe 'specifying viewer only' do subject { MongoidUser.with_all_roles(:viewer).sort_by(&:id) } it 'returns only viewers' do subject.must_equal [@admin_author_viewer, @author_viewer, @viewer].sort_by(&:id) end it "doesn't return non authors" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @author_only end end describe 'specifying admin and author' do subject { MongoidUser.with_all_roles(:admin, :author).sort_by(&:id) } it 'returns only admins and authors' do subject.must_equal [@admin_author_viewer].sort_by(&:id) end it "doesn't return non admin and authors" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @admin_only subject.wont_include @viewer end end describe 'specifying admin and viewer' do subject { MongoidUser.with_all_roles(:admin, :viewer).sort_by(&:id) } it 'returns only admins and viewers' do subject.must_equal [@admin_author_viewer].sort_by(&:id) end it "doesn't return non admins or viewers" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @admin_only subject.wont_include @viewer end end describe 'specifying author and viewer' do subject { MongoidUser.with_all_roles(:author, :viewer).sort_by(&:id) } it 'returns only authors and viewers' do subject.must_equal [@admin_author_viewer, @author_viewer].sort_by(&:id) end it "doesn't return non authors or viewers" do subject.wont_include @no_role subject.wont_include @admin_only subject.wont_include @author_only subject.wont_include @viewer end end describe 'specifying admin, author and viewer' do subject { MongoidUser.with_all_roles(:admin, :author, :viewer).sort_by(&:id) } it 'returns only admins, authors and viewers' do subject.must_equal [@admin_author_viewer].sort_by(&:id) end it "doesn't return non admins, authors or viewers" do subject.wont_include @no_role subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @admin_only subject.wont_include @viewer end end end describe 'with_only_roles' do describe 'specifying one role' do subject { MongoidUser.with_only_roles(:admin).sort_by(&:id) } it 'returns users with just that role' do subject.must_equal [@admin_only].sort_by(&:id) end it "doesn't return any other users" do subject.wont_include @no_role subject.wont_include @admin_author_viewer subject.wont_include @author_viewer subject.wont_include @author_only subject.wont_include @viewer end end describe 'specifying multiple roles' do subject { MongoidUser.with_only_roles(:author, :viewer).sort_by(&:id) } it 'returns only users with no more or less roles' do subject.must_equal [@author_viewer].sort_by(&:id) end it "doesn't return any other users" do subject.wont_include @no_role subject.wont_include @admin_author_viewer subject.wont_include @admin_only subject.wont_include @author_only subject.wont_include @viewer end end end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/canard.rb
lib/canard.rb
# frozen_string_literal: true require 'forwardable' require 'cancan' require 'role_model' require 'canard/abilities' require 'canard/version' require 'canard/user_model' require 'canard/find_abilities' require 'ability' require 'canard/railtie' if defined?(Rails) && Rails::VERSION::MAJOR >= 3
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/ability.rb
lib/ability.rb
# frozen_string_literal: true # Canard provides a CanCan Ability class for you. The Canard Ability class # looks for and applies abilities for the object passed when a new Ability # instance is initialized. # # If the passed object has a reference to user the user is set to that. # Otherwise the passed object is assumed to be the user. This gives the # flexibility to have a seperate model for authorization from the model used # to authenticate the user. # # Abilities are applied in the order they are set with the acts_as_user method # for example for the User model # # class User < ActiveRecord::Base # # acts_as_user :roles => :manager, :admin # # end # # the abilities would be applied in the order: users, managers, admins # with each subsequent set of abilities building on or overriding the existing # abilities. # # If there is no object passed to the Ability.new method a guest ability is # created and Canard will look for a guests.rb amongst the ability definitions # and give the guest those abilities. class Ability include CanCan::Ability extend Forwardable attr_reader :user def_delegators :Canard, :ability_definitions, :ability_key def initialize(object = nil) # If object has a user attribute set the user from it otherwise assume # this is the user. @user = object.respond_to?(:user) ? object.user : object add_base_abilities add_roles_abilities if @user.respond_to?(:roles) end protected def add_base_abilities if @user # Add the base user abilities. user_class_name = String(@user.class.name) append_abilities user_class_name unless user_class_name.empty? else # If user not set then lets create a guest @user = Object.new append_abilities :guest end end def add_roles_abilities @user.roles.each { |role| append_abilities(role) } end def append_abilities(dirty_key) key = ability_key(dirty_key) instance_eval(&ability_definitions[key]) if ability_definitions.key?(key) end def includes_abilities_of(*other_roles) other_roles.each { |other_role| append_abilities(other_role) } end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/generators/ability_definition.rb
lib/generators/ability_definition.rb
# frozen_string_literal: true require 'active_support/inflector' class AbilityDefinition # :nodoc: attr_accessor :cans, :cannots def self.parse(definitions) @@ability_definitions ||= {} limitation, ability_list, model_list = definitions.split(':') ability_names = extract(ability_list) model_names = extract(model_list) model_names.each do |model_name| definition = @@ability_definitions[model_name] || AbilityDefinition.new definition.merge(limitation.pluralize, ability_names) @@ability_definitions[model_name] = definition end end def self.extract(string) string.gsub(/[\[\]\s]/, '').split(',') end def self.models @@ability_definitions end def initialize @cans = [] @cannots = [] end def merge(limitation, ability_names) combined_ability_names = instance_variable_get("@#{limitation}") | ability_names instance_variable_set("@#{limitation}", combined_ability_names) end def can @cans end def cannot @cannots end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/generators/rspec/ability/ability_generator.rb
lib/generators/rspec/ability/ability_generator.rb
# frozen_string_literal: true require 'generators/rspec' require_relative '../../ability_definition' module Rspec module Generators class AbilityGenerator < Base @_rspec_source_root = File.expand_path('templates', __dir__) argument :ability_definitions, type: :array, default: [], banner: 'can:abilities:models cannot:abilities:models' def generate_ability_spec template 'abilities_spec.rb.erb', "spec/abilities/#{file_name.pluralize}_spec.rb" end private def definitions ability_definitions.each { |definition| AbilityDefinition.parse(definition) } AbilityDefinition.models.sort.each do |model, definition| yield model, definition end end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/generators/canard/ability/ability_generator.rb
lib/generators/canard/ability/ability_generator.rb
# frozen_string_literal: true require_relative '../../ability_definition' module Canard module Generators class AbilityGenerator < Rails::Generators::NamedBase # :nodoc: source_root File.expand_path('templates', __dir__) argument :ability_definitions, type: :array, default: [], banner: 'can:[read,update]:[user,account] cannot:[create,destroy]:user' def generate_ability template 'abilities.rb.erb', Abilities.default_path + "/#{file_name.pluralize}.rb" end hook_for :test_framework, as: 'ability' private def definitions ability_definitions.each { |definition| AbilityDefinition.parse(definition) } AbilityDefinition.models.sort.each do |model, definition| yield model, definition end end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/canard/abilities.rb
lib/canard/abilities.rb
# frozen_string_literal: true module Canard class Abilities # :nodoc: @definitions = {} @default_path = 'app/abilities' class << self extend Forwardable def_delegators :Canard, :ability_key attr_accessor :default_path attr_writer :definition_paths attr_reader :definitions def definition_paths @definition_paths ||= [@default_path] end def for(name, &block) raise ArgumentError, 'No block of ability definitions given' unless block_given? key = ability_key(name) @definitions[key] = block end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/canard/version.rb
lib/canard/version.rb
# frozen_string_literal: true module Canard VERSION = '0.6.2.pre' end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/canard/railtie.rb
lib/canard/railtie.rb
# frozen_string_literal: true module Canard class Railtie < Rails::Railtie # :nodoc: initializer 'canard.no_eager_loading', before: 'before_eager_loading' do |app| ActiveSupport::Dependencies.autoload_paths.reject! { |path| Canard.load_paths.include?(path) } # Don't eagerload our configs, we'll deal with them ourselves app.config.eager_load_paths = app.config.eager_load_paths.reject do |path| Canard.load_paths.include?(path) end app.config.watchable_dirs.merge! Hash[Canard.load_paths.product([[:rb]])] if app.config.respond_to?(:watchable_dirs) end initializer 'canard.active_record' do |_app| ActiveSupport.on_load :active_record do require 'canard/adapters/active_record' Canard::Abilities.default_path = File.expand_path('app/abilities', Rails.root) extend Canard::UserModel Canard.find_abilities end end initializer 'canard.mongoid' do |_app| require 'canard/adapters/mongoid' if defined?(Mongoid) end initializer 'canard.abilities_reloading', after: 'action_dispatch.configure' do |_app| reloader = rails5? ? ActiveSupport::Reloader : ActionDispatch::Reloader reloader.to_prepare { Canard.find_abilities } if reloader.respond_to?(:to_prepare) end rake_tasks do load File.expand_path('../tasks/canard.rake', __dir__) end private def rails5? ActionPack::VERSION::MAJOR == 5 end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/canard/user_model.rb
lib/canard/user_model.rb
# frozen_string_literal: true module Canard # Canard applies roles to a model using the acts_as_user class method. The following User model # will be given the :manager and :admin roles # # class User < ActiveRecord::Base # # acts_as_user :roles => [:manager, :admin] # # end # # If using Canard with a non ActiveRecord class you can still assign roles but you will need to # extend the class with Canard::UserModel and add a roles_mask attribute. # # class User # # extend Canard::UserModel # # attr_accessor :roles_mask # # acts_as_user :roles => [:manager, :admin] # # end # # You can choose the attribute used for the roles_mask by specifying :roles_mask. If no # roles_mask is specified it uses RoleModel's default of 'roles_mask' # # acts_as_user :roles_mask => :my_roles_mask, :roles => [:manager, :admin] # # == Scopes # # Beyond applying the roles to the model, acts_as_user also creates some useful scopes for # ActiveRecord models; # # User.with_any_role(:manager, :admin) # # returns all the managers and admins # # User.with_all_roles(:manager, :admin) # # returns only the users with both the manager and admin roles # # User.admins # # returns all the admins as # # User.managers # # returns all the users with the maager role likewise # # User.non_admins # # returns all the users who don't have the admin role and # # User.non_managers # # returns all the users who don't have the manager role. module UserModel def acts_as_user(*args) include RoleModel include InstanceMethods options = args.last.is_a?(Hash) ? args.pop : {} if defined?(ActiveRecord) && self < ActiveRecord::Base extend Adapters::ActiveRecord elsif defined?(Mongoid) && included_modules.include?(Mongoid::Document) extend Adapters::Mongoid field (options[:roles_mask] || :roles_mask), type: Integer end roles_attribute options[:roles_mask] if options.key?(:roles_mask) roles options[:roles] if options.key?(:roles) && has_roles_mask_accessors? add_role_scopes(prefix: options[:prefix]) if respond_to?(:add_role_scopes, true) end private # This is overridden by the ActiveRecord adapter as the attribute accessors # don't show up in instance_methods. def has_roles_mask_accessors? instance_method_names = instance_methods.map(&:to_s) [roles_attribute_name.to_s, "#{roles_attribute_name}="].all? do |accessor| instance_method_names.include?(accessor) end end module InstanceMethods # :nodoc: def ability @ability ||= Ability.new(self) end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/canard/find_abilities.rb
lib/canard/find_abilities.rb
# frozen_string_literal: true module Canard # :nodoc: def self.ability_definitions Abilities.definitions end def self.ability_key(class_name) String(class_name) .gsub('::', '') .gsub(/(.)([A-Z])/, '\1_\2') .downcase .to_sym end def self.load_paths Abilities.definition_paths.map { |path| File.expand_path(path) } end def self.find_abilities #:nodoc: load_paths.each do |path| Dir[File.join(path, '**', '*.rb')].sort.each do |file| load file end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/canard/adapters/active_record.rb
lib/canard/adapters/active_record.rb
# frozen_string_literal: true module Canard module Adapters module ActiveRecord # :nodoc: private def add_role_scopes(**options) define_scopes(options) if active_record_table_exists? end def define_scopes(options) valid_roles.each do |role| define_scopes_for_role role, options[:prefix] end # TODO: change hard coded :role_mask to roles_attribute_name define_singleton_method(:with_any_role) do |*roles| where("#{role_mask_column} & :role_mask > 0", role_mask: mask_for(*roles)) end define_singleton_method(:with_all_roles) do |*roles| where("#{role_mask_column} & :role_mask = :role_mask", role_mask: mask_for(*roles)) end define_singleton_method(:with_only_roles) do |*roles| where("#{role_mask_column} = :role_mask", role_mask: mask_for(*roles)) end end def active_record_table_exists? respond_to?(:table_exists?) && table_exists? rescue ::ActiveRecord::NoDatabaseError, StandardError false end # TODO: extract has_roles_attribute? and change to has_roles_attribute? || super def has_roles_mask_accessors? active_record_table_exists? && column_names.include?(roles_attribute_name.to_s) || super end def define_scopes_for_role(role, prefix = nil) include_scope = [prefix, String(role).pluralize].compact.join('_') exclude_scope = "non_#{include_scope}" define_singleton_method(include_scope) do where("#{role_mask_column} & :role_mask > 0", role_mask: mask_for(role)) end define_singleton_method(exclude_scope) do where("#{role_mask_column} & :role_mask = 0 or #{role_mask_column} is null", role_mask: mask_for(role)) end end def role_mask_column "#{quoted_table_name}.#{connection.quote_column_name roles_attribute_name}" end end end end
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
james2m/canard
https://github.com/james2m/canard/blob/6040110ed79bbb8051d0c487c77ba2160e404516/lib/canard/adapters/mongoid.rb
lib/canard/adapters/mongoid.rb
# frozen_string_literal: true module Canard module Adapters module Mongoid # :nodoc: private def add_role_scopes(*args) options = args.extract_options! valid_roles.each do |role| define_scopes_for_role role, options[:prefix] end define_singleton_method(:with_any_role) do |*roles| where("(this.#{roles_attribute_name} & #{mask_for(*roles)}) > 0") end define_singleton_method(:with_all_roles) do |*roles| where("(this.#{roles_attribute_name} & #{mask_for(*roles)}) === #{mask_for(*roles)}") end define_singleton_method(:with_only_roles) do |*roles| where("this.#{roles_attribute_name} === #{mask_for(*roles)}") end end def has_roles_mask_accessors? fields.include?(roles_attribute_name.to_s) || super end def define_scopes_for_role(role, prefix = nil) include_scope = [prefix, String(role).pluralize].compact.join('_') exclude_scope = "non_#{include_scope}" scope include_scope, -> { where("(this.#{roles_attribute_name} & #{mask_for(role)}) > 0") } scope exclude_scope, lambda { any_of( { roles_attribute_name => { '$exists' => false } }, { roles_attribute_name => nil }, '$where' => "(this.#{roles_attribute_name} & #{mask_for(role)}) === 0" ) } end end end end Mongoid::Document::ClassMethods.send(:include, Canard::Adapters::Mongoid) Mongoid::Document::ClassMethods.send(:include, Canard::UserModel) Canard.find_abilities
ruby
MIT
6040110ed79bbb8051d0c487c77ba2160e404516
2026-01-04T17:55:41.739331Z
false
dtaniwaki/mandriller
https://github.com/dtaniwaki/mandriller/blob/c9f6c0d840dd78547491504fe4450bf2b1317dce/spec/spec_helper.rb
spec/spec_helper.rb
require 'rubygems' require 'coveralls' Coveralls.wear! require 'mandriller' Dir[File.join(File.dirname(__FILE__), "support/**/*.rb")].each {|f| require f } RSpec.configure do |config| config.before :suite do ActionMailer::Base.delivery_method = :test end end
ruby
MIT
c9f6c0d840dd78547491504fe4450bf2b1317dce
2026-01-04T17:55:41.600973Z
false
dtaniwaki/mandriller
https://github.com/dtaniwaki/mandriller/blob/c9f6c0d840dd78547491504fe4450bf2b1317dce/spec/mandriller/settings_methods_spec.rb
spec/mandriller/settings_methods_spec.rb
require 'spec_helper' describe Mandriller::SettingsMethods do let(:klass) do Class.new do include Mandriller::SettingsMethods end end subject do klass.class_eval do define_settings_methods :foo end klass end describe "::define_settings_methods" do it "defines the methods" do expect(subject.private_methods).to include(:set_mandrill_setting_foo) expect(subject.private_methods).to include(:set_foo) expect(subject).to respond_to(:mandrill_foo) expect(subject.private_instance_methods).to include(:set_mandrill_setting_foo) expect(subject.private_instance_methods).to include(:set_foo) expect(subject.private_instance_methods).to include(:get_mandrill_setting_foo) instance = subject.new expect(instance.instance_variable_defined?("@mandrill_foo")).to eq(false) end it "sets the instance variable" do instance = subject.new instance.send :set_mandrill_setting_foo, 'foo' expect(instance.instance_variable_get("@mandrill_foo")).to eq('foo') end it "sets the class attribute" do subject.send :set_mandrill_setting_foo, 'foo' expect(subject.mandrill_foo).to eq('foo') end it "gets the value as is" do instance = subject.new instance.send :set_mandrill_setting_foo, 'foo' expect(instance.send(:get_mandrill_setting_foo)).to eq('foo') end context "with default option" do subject do klass.class_eval do define_settings_methods :foo, default: 'bar' end klass end it "sets the instance variable with default value" do instance = subject.new instance.send :set_mandrill_setting_foo expect(instance.instance_variable_get("@mandrill_foo")).to eq('bar') end it "sets the class attribute with default value" do subject.send :set_mandrill_setting_foo expect(subject.mandrill_foo).to eq('bar') end end context "with getter option" do subject do klass.class_eval do define_settings_methods :foo, getter: lambda { |v| v.to_sym } end klass end it "gets the value as is" do instance = subject.new instance.send :set_mandrill_setting_foo, 'foo' expect(instance.send(:get_mandrill_setting_foo)).to eq(:foo) end end end describe "#is_mandrill_setting_defined?" do it "returns true for the value set globally" do subject.send :set_mandrill_setting_foo, 1 instance = subject.new expect(instance.send(:is_mandrill_setting_defined?, :foo)).to eq(true) end it "returns true for the value set localy" do instance = subject.new instance.send :set_mandrill_setting_foo, 2 expect(instance.send(:is_mandrill_setting_defined?, :foo)).to eq(true) end it "returns false for non set value" do instance = subject.new expect(instance.send(:is_mandrill_setting_defined?, :foo)).to eq(false) end end describe "#get_mandrill_setting" do it "delegates to the setting method" do instance = subject.new ret = double expect(instance).to receive(:get_mandrill_setting_foo).and_return(ret) expect(instance.send(:get_mandrill_setting, :foo)).to eq(ret) end end end
ruby
MIT
c9f6c0d840dd78547491504fe4450bf2b1317dce
2026-01-04T17:55:41.600973Z
false
dtaniwaki/mandriller
https://github.com/dtaniwaki/mandriller/blob/c9f6c0d840dd78547491504fe4450bf2b1317dce/spec/mandriller/base_spec.rb
spec/mandriller/base_spec.rb
require 'spec_helper' describe Mandriller::Base do let(:global_settings) { lambda{} } let(:local_settings) { lambda{} } let(:klass) do gs = global_settings ls = local_settings klass = Class.new(Mandriller::Base) do self.mailer_name = 'foo_mailer' instance_exec(&gs) define_method :foo do instance_exec(&ls) mail from: 'from@example.com', to: ['to@example.com'] end end allow_any_instance_of(ActionMailer::Base).to receive(:each_template).and_return('') klass end subject { klass.foo } BOOLEAN_SETTINGS = { auto_text: 'X-MC-Autotext', auto_html: 'X-MC-AutoHtml', url_strip_qs: 'X-MC-URLStripQS', preserve_recipients: 'X-MC-PreserveRecipients', inline_css: 'X-MC-InlineCSS', view_content_link: 'X-MC-ViewContentLink', important: 'X-MC-Important', } BOOLEAN_SETTINGS.each do |key, header| describe "#{header} header" do context "no set" do it_behaves_like "without header", header end context "set by #set_#{key}" do context "set default" do let(:local_settings) { lambda{ __send__("set_#{key}") } } it_behaves_like "with header", header, true end context "set true" do let(:local_settings) { lambda{ __send__("set_#{key}", true) } } it_behaves_like "with header", header, true end context "set false" do let(:local_settings) { lambda{ __send__("set_#{key}", false) } } it_behaves_like "with header", header, false end end context "set by ::set_#{key}" do context "set default" do let(:global_settings) { lambda{ __send__("set_#{key}") } } it_behaves_like "with header", header, true end context "set true" do let(:global_settings) { lambda{ __send__("set_#{key}", true) } } it_behaves_like "with header", header, true end context "set false" do let(:global_settings) { lambda{ __send__("set_#{key}", false) } } end end context "set by both #set_#{key} and ::set_#{key}" do context "set true globally and set false locally" do let(:global_settings) { lambda{ __send__("set_#{key}", true) } } let(:local_settings) { lambda{ __send__("set_#{key}", false) } } it_behaves_like "with header", header, false end context "set false globally and set true locally" do let(:global_settings) { lambda{ __send__("set_#{key}", false) } } let(:local_settings) { lambda{ __send__("set_#{key}", true) } } it_behaves_like "with header", header, true end context "set value globally but set nil locally" do let(:global_settings) { lambda{ __send__("set_#{key}", true) } } let(:local_settings) { lambda{ __send__("set_#{key}", nil) } } it_behaves_like "without header", header end end end end STRING_SETTINGS = { tracking_domain: 'X-MC-TrackingDomain', signing_domain: 'X-MC-SigningDomain', subaccount: 'X-MC-Subaccount', bcc_address: 'X-MC-BccAddress', ip_pool: 'X-MC-IpPool', google_analytics_campaign: 'X-MC-GoogleAnalyticsCampaign', return_path_domain: 'X-MC-ReturnPathDomain', } STRING_SETTINGS.each do |key, header| describe "#{header} header" do context "no set" do it_behaves_like "without header", header end context "set by #set_#{key}" do let(:local_settings) { lambda{ __send__("set_#{key}", 'local-string') } } it_behaves_like "with header", header, 'local-string' end context "set by ::set_#{key}" do let(:global_settings) { lambda{ __send__("set_#{key}", 'global-string') } } it_behaves_like "with header", header, 'global-string' end context "set by both #set_#{key} and ::set_#{key}" do context "set value globally and set value locally" do let(:global_settings) { lambda{ __send__("set_#{key}", 'global-string') } } let(:local_settings) { lambda{ __send__("set_#{key}", 'local-string') } } it_behaves_like "with header", header, 'local-string' end context "set value globally but set nil locally" do let(:global_settings) { lambda{ __send__("set_#{key}", 'global-string') } } let(:local_settings) { lambda{ __send__("set_#{key}", nil) } } it_behaves_like "without header", header end end end end JSON_SETTINGS = { metadata: 'X-MC-Metadata', merge_vars: 'X-MC-MergeVars', } JSON_SETTINGS.each do |key, header| describe "#{header} header" do context "no set" do it_behaves_like "without header", header end context "set by #set_#{key}" do let(:local_settings) { lambda{ __send__("set_#{key}", {local: 1}) } } it_behaves_like "with header", header, '{"local":1}' end context "set by ::set_#{key}" do let(:global_settings) { lambda{ __send__("set_#{key}", {global: 1}) } } it_behaves_like "with header", header, '{"global":1}' end context "set by both #set_#{key} and ::set_#{key}" do context "set value globally and set value locally" do let(:global_settings) { lambda{ __send__("set_#{key}", {global: 1}) } } let(:local_settings) { lambda{ __send__("set_#{key}", {local: 1}) } } it_behaves_like "with header", header, '{"local":1}' end context "set value globally but set nil locally" do let(:global_settings) { lambda{ __send__("set_#{key}", {global: 1}) } } let(:local_settings) { lambda{ __send__("set_#{key}", nil) } } it_behaves_like "without header", header end end end end ARRAY_SETTINGS = { google_analytics: 'X-MC-GoogleAnalytics', tags: 'X-MC-Tags', } ARRAY_SETTINGS.each do |key, header| describe "#{header} header" do context "no set" do it_behaves_like "without header", header end context "set by #set_#{key}" do let(:local_settings) { lambda{ __send__("set_#{key}", ['string1', 'string2']) } } it_behaves_like "with header", header, 'string1,string2' end context "set by ::set_#{key}" do let(:global_settings) { lambda{ __send__("set_#{key}", ['string1', 'string2']) } } it_behaves_like "with header", header, 'string1,string2' end context "set by both #set_#{key} and ::set_#{key}" do context "set value globally and set value locally" do let(:global_settings) { lambda{ __send__("set_#{key}", ['string1', 'string2']) } } let(:local_settings) { lambda{ __send__("set_#{key}", ['string2', 'string3']) } } it_behaves_like "with header", header, 'string2,string3' end context "set value globally but set nil locally" do let(:global_settings) { lambda{ __send__("set_#{key}", ['string1', 'string2']) } } let(:local_settings) { lambda{ __send__("set_#{key}", nil) } } it_behaves_like "without header", header end end end end DATETIME_SETTINGS = { send_at: 'X-MC-SendAt', } DATETIME_SETTINGS.each do |key, header| describe "#{header} header" do context "no set" do it_behaves_like "without header", header end context "set by #set_#{key}" do let(:local_settings) { lambda{ __send__("set_#{key}", DateTime.new(2001, 1, 2, 3, 4, 5)) } } it_behaves_like "with header", header, '2001-01-02 03:04:05' end context "set by ::set_#{key}" do let(:global_settings) { lambda{ __send__("set_#{key}", DateTime.new(2001, 1, 2, 3, 4, 5)) } } it_behaves_like "with header", header, '2001-01-02 03:04:05' end context "set by both #set_#{key} and ::set_#{key}" do context "set value globally and set value locally" do let(:global_settings) { lambda{ __send__("set_#{key}", DateTime.new(2001, 1, 2, 3, 4, 5)) } } let(:local_settings) { lambda{ __send__("set_#{key}", DateTime.new(2001, 1, 2, 3, 4, 6)) } } it_behaves_like "with header", header, '2001-01-02 03:04:06' end context "set value globally but set nil locally" do let(:global_settings) { lambda{ __send__("set_#{key}", DateTime.new(2001, 1, 2, 3, 4, 5)) } } let(:local_settings) { lambda{ __send__("set_#{key}", nil) } } it_behaves_like "without header", header end end end end describe "X-MC-Track header" do header = "X-MC-Track" context "no set" do it_behaves_like "without header", header end context "set by #set_open_track" do let(:local_settings) { lambda{ set_open_track } } it_behaves_like "with header", 'X-MC-Track', 'opens' end context "set by #set_open_track" do let(:global_settings) { lambda{ set_open_track } } it_behaves_like "with header", 'X-MC-Track', 'opens' end context "set by #set_open_track" do let(:local_settings) { lambda{ set_click_track :all } } it_behaves_like "with header", 'X-MC-Track', 'clicks_all' context "invalid type" do let(:local_settings) { lambda{ set_click_track :invalid } } it_behaves_like "raise an exception", Mandriller::InvalidHeaderValue end end context "set by ::set_open_track" do let(:global_settings) { lambda{ set_click_track :all } } it_behaves_like "with header", 'X-MC-Track', 'clicks_all' end context "set by both ::set_open_track and ::set_click_track" do let(:global_settings) { lambda{ set_open_track; set_click_track :all } } it_behaves_like "with header", 'X-MC-Track', 'opens,clicks_all' end end describe "X-MC-Template header" do key = "template" header = "X-MC-Template" context "no set" do it_behaves_like "without header", header end context "set by #set_#{key}" do let(:local_settings) { lambda{ __send__("set_#{key}", 'template1', 'block1') } } it_behaves_like "with header", header, 'template1|block1' end context "set by ::set_#{key}" do let(:global_settings) { lambda{ __send__("set_#{key}", 'template1', 'block1') } } it_behaves_like "with header", header, 'template1|block1' end context "set by both #set_#{key} and ::set_#{key}" do context "set value globally and set value locally" do let(:global_settings) { lambda{ __send__("set_#{key}", 'template1', 'block1') } } let(:local_settings) { lambda{ __send__("set_#{key}", 'template2', 'block2') } } it_behaves_like "with header", header, 'tempalte2|block2' end context "set value globally but set nil locally" do let(:global_settings) { lambda{ __send__("set_#{key}", 'template1', 'block1') } } let(:local_settings) { lambda{ __send__("set_#{key}", nil) } } it_behaves_like "without header", header end end end end
ruby
MIT
c9f6c0d840dd78547491504fe4450bf2b1317dce
2026-01-04T17:55:41.600973Z
false
dtaniwaki/mandriller
https://github.com/dtaniwaki/mandriller/blob/c9f6c0d840dd78547491504fe4450bf2b1317dce/spec/support/action_mailer.rb
spec/support/action_mailer.rb
deliver_method = ActionMailer.respond_to?(:version) && ActionMailer.version.to_s.to_f >= 4.2 ? :deliver_now! : :deliver! shared_examples "with header" do |header, value| it "sets header #{header}" do expect { subject.__send__(deliver_method) }.to change { ActionMailer::Base.deliveries.count }.by(1) m = ActionMailer::Base.deliveries.last expect(m.header.to_s).to match(/(\r\n)?#{header}: #{value}(\r\n)?/) end end shared_examples "without header" do |header| it "does not set header #{header}" do expect { subject.__send__(deliver_method) }.to change { ActionMailer::Base.deliveries.count }.by(1) m = ActionMailer::Base.deliveries.last expect(m.header.to_s).not_to match(/(\r\n)?#{header}: [^\r]*(\r\n)?/) end end shared_examples "raise an exception" do |exception| it "raises #{exception}" do expect { expect { subject.__send__(deliver_method) }.to raise_error(exception) }.to change { ActionMailer::Base.deliveries.count }.by(0) end end
ruby
MIT
c9f6c0d840dd78547491504fe4450bf2b1317dce
2026-01-04T17:55:41.600973Z
false
dtaniwaki/mandriller
https://github.com/dtaniwaki/mandriller/blob/c9f6c0d840dd78547491504fe4450bf2b1317dce/lib/mandriller.rb
lib/mandriller.rb
require 'mandriller/version' require 'mandriller/errors' require 'mandriller/base' module Mandriller end
ruby
MIT
c9f6c0d840dd78547491504fe4450bf2b1317dce
2026-01-04T17:55:41.600973Z
false
dtaniwaki/mandriller
https://github.com/dtaniwaki/mandriller/blob/c9f6c0d840dd78547491504fe4450bf2b1317dce/lib/mandriller/version.rb
lib/mandriller/version.rb
module Mandriller VERSION = '0.2.0' end
ruby
MIT
c9f6c0d840dd78547491504fe4450bf2b1317dce
2026-01-04T17:55:41.600973Z
false
dtaniwaki/mandriller
https://github.com/dtaniwaki/mandriller/blob/c9f6c0d840dd78547491504fe4450bf2b1317dce/lib/mandriller/errors.rb
lib/mandriller/errors.rb
module Mandriller class Exception < ::Exception; end; class InvalidHeaderValue < Exception; end; end
ruby
MIT
c9f6c0d840dd78547491504fe4450bf2b1317dce
2026-01-04T17:55:41.600973Z
false