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
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/lib/mixlib/shellout/exceptions.rb
lib/mixlib/shellout/exceptions.rb
module Mixlib class ShellOut class Error < RuntimeError; end class ShellCommandFailed < Error; end class CommandTimeout < Error; end class InvalidCommandOption < Error; end class EmptyWindowsCommand < ShellCommandFailed; end end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/lib/mixlib/shellout/unix.rb
lib/mixlib/shellout/unix.rb
# frozen_string_literal: true # # Author:: Daniel DeLeo (<dan@chef.io>) # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "fileutils" unless defined?(FileUtils) module Mixlib class ShellOut module Unix # Option validation that is unix specific def validate_options(opts) if opts[:elevated] raise InvalidCommandOption, "Option `elevated` is supported for Powershell commands only" end end # Whether we're simulating a login shell def using_login? login && user end # Helper method for sgids def all_seconderies ret = [] Etc.endgrent while ( g = Etc.getgrent ) ret << g end Etc.endgrent ret end # The secondary groups that the subprocess will switch to. # Currently valid only if login is used, and is set # to the user's secondary groups def sgids return nil unless using_login? user_name = Etc.getpwuid(uid).name all_seconderies.select { |g| g.mem.include?(user_name) }.map(&:gid) end # The environment variables that are deduced from simulating logon # Only valid if login is used def logon_environment return {} unless using_login? entry = Etc.getpwuid(uid) # According to `man su`, the set fields are: # $HOME, $SHELL, $USER, $LOGNAME, $PATH, and $IFS # Values are copied from "shadow" package in Ubuntu 14.10 { "HOME" => entry.dir, "SHELL" => entry.shell, "USER" => entry.name, "LOGNAME" => entry.name, "PATH" => "/sbin:/bin:/usr/sbin:/usr/bin", "IFS" => "\t\n" } end # Merges the two environments for the process def process_environment logon_environment.merge(environment) end # Run the command, writing the command's standard out and standard error # to +stdout+ and +stderr+, and saving its exit status object to +status+ # === Returns # returns +self+; +stdout+, +stderr+, +status+, and +exitstatus+ will be # populated with results of the command. # === Raises # * Errno::EACCES when you are not privileged to execute the command # * Errno::ENOENT when the command is not available on the system (or not # in the current $PATH) # * Chef::Exceptions::CommandTimeout when the command does not complete # within +timeout+ seconds (default: 600s). When this happens, ShellOut # will send a TERM and then KILL to the entire process group to ensure # that any grandchild processes are terminated. If the invocation of # the child process spawned multiple child processes (which commonly # happens if the command is passed as a single string to be interpreted # by bin/sh, and bin/sh is not bash), the exit status object may not # contain the correct exit code of the process (of course there is no # exit code if the command is killed by SIGKILL, also). def run_command @child_pid = fork_subprocess @reaped = false configure_parent_process_file_descriptors # CHEF-3390: Marshall.load on Ruby < 1.8.7p369 also has a GC bug related # to Marshall.load, so try disabling GC first. propagate_pre_exec_failure @status = nil @result = nil @execution_time = 0 write_to_child_stdin until @status ready_buffers = attempt_buffer_read unless ready_buffers @execution_time += READ_WAIT_TIME if @execution_time >= timeout && !@result # kill the bad proccess reap_errant_child # read anything it wrote when we killed it attempt_buffer_read # raise raise CommandTimeout, "Command timed out after #{@execution_time.to_i}s:\n#{format_for_exception}" end end attempt_reap end self rescue Errno::ENOENT # When ENOENT happens, we can be reasonably sure that the child process # is going to exit quickly, so we use the blocking variant of waitpid2 reap raise ensure reap_errant_child if should_reap? # make one more pass to get the last of the output after the # child process dies attempt_buffer_read(0) # no matter what happens, turn the GC back on, and hope whatever busted # version of ruby we're on doesn't allocate some objects during the next # GC run. GC.enable close_all_pipes end private def set_user if user Process.uid = uid Process.euid = uid end end def set_group if group Process.egid = gid Process.gid = gid end end def set_secondarygroups if sgids Process.groups = sgids end end def set_environment # user-set variables should override the login ones process_environment.each do |env_var, value| ENV[env_var] = value end end def set_umask File.umask(umask) if umask end def set_cwd Dir.chdir(cwd) if cwd end def set_cgroup new_cgroup_path = "/sys/fs/cgroup/#{cgroup}" # Create cgroup if missing unless Dir.exist?(new_cgroup_path) FileUtils.mkdir_p new_cgroup_path end # Migrate current process to newly cgroup, any subprocesses will run inside new cgroup File.write("#{new_cgroup_path}/cgroup.procs", Process.pid.to_s) end # Since we call setsid the child_pgid will be the child_pid, set to negative here # so it can be directly used in arguments to kill, wait, etc. def child_pgid -@child_pid end def initialize_ipc @stdin_pipe, @stdout_pipe, @stderr_pipe, @process_status_pipe = IO.pipe, IO.pipe, IO.pipe, IO.pipe @process_status_pipe.last.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) end def child_stdin @stdin_pipe[1] end def child_stdout @stdout_pipe[0] end def child_stderr @stderr_pipe[0] end def child_process_status @process_status_pipe[0] end def close_all_pipes child_stdin.close unless child_stdin.closed? child_stdout.close unless child_stdout.closed? child_stderr.close unless child_stderr.closed? child_process_status.close unless child_process_status.closed? end # Replace stdout, and stderr with pipes to the parent, and close the # reader side of the error marshaling side channel. # # If there is no input, close STDIN so when we exec, # the new program will know it's never getting input ever. def configure_subprocess_file_descriptors process_status_pipe.first.close # HACK: for some reason, just STDIN.close isn't good enough when running # under ruby 1.9.2, so make it good enough: stdin_pipe.last.close STDIN.reopen stdin_pipe.first stdin_pipe.first.close unless input stdout_pipe.first.close STDOUT.reopen stdout_pipe.last stdout_pipe.last.close stderr_pipe.first.close STDERR.reopen stderr_pipe.last stderr_pipe.last.close STDOUT.sync = STDERR.sync = true STDIN.sync = true if input end def configure_parent_process_file_descriptors # Close the sides of the pipes we don't care about stdin_pipe.first.close stdin_pipe.last.close unless input stdout_pipe.last.close stderr_pipe.last.close process_status_pipe.last.close # Get output as it happens rather than buffered child_stdin.sync = true if input child_stdout.sync = true child_stderr.sync = true true end # Some patch levels of ruby in wide use (in particular the ruby 1.8.6 on OSX) # segfault when you IO.select a pipe that's reached eof. Weak sauce. def open_pipes @open_pipes ||= [child_stdout, child_stderr, child_process_status] end # Keep this unbuffered for now def write_to_child_stdin return unless input child_stdin << input child_stdin.close # Kick things off end def attempt_buffer_read(timeout = READ_WAIT_TIME) ready = IO.select(open_pipes, nil, nil, timeout) if ready read_stdout_to_buffer if ready.first.include?(child_stdout) read_stderr_to_buffer if ready.first.include?(child_stderr) read_process_status_to_buffer if ready.first.include?(child_process_status) end ready end def read_stdout_to_buffer while ( chunk = child_stdout.read_nonblock(READ_SIZE) ) @stdout << chunk @live_stdout << chunk if @live_stdout end rescue Errno::EAGAIN rescue EOFError open_pipes.delete(child_stdout) end def read_stderr_to_buffer while ( chunk = child_stderr.read_nonblock(READ_SIZE) ) @stderr << chunk @live_stderr << chunk if @live_stderr end rescue Errno::EAGAIN rescue EOFError open_pipes.delete(child_stderr) end def read_process_status_to_buffer while ( chunk = child_process_status.read_nonblock(READ_SIZE) ) @process_status << chunk end rescue Errno::EAGAIN rescue EOFError open_pipes.delete(child_process_status) end def cgroupv2_available? File.read("/proc/mounts").match?(%r{^cgroup2 /sys/fs/cgroup}) end def fork_subprocess initialize_ipc fork do # Child processes may themselves fork off children. A common case # is when the command is given as a single string (instead of # command name plus Array of arguments) and /bin/sh does not # support the "ONESHOT" optimization (where sh -c does exec without # forking). To support cleaning up all the children, we need to # ensure they're in a unique process group. # # We use setsid here to abandon our controlling tty and get a new session # and process group that are set to the pid of the child process. Process.setsid configure_subprocess_file_descriptors if cgroup && cgroupv2_available? set_cgroup end set_secondarygroups set_group set_user set_environment set_umask set_cwd begin command.is_a?(Array) ? exec(*command, close_others: true) : exec(command, close_others: true) raise "forty-two" # Should never get here rescue Exception => e Marshal.dump(e, process_status_pipe.last) process_status_pipe.last.flush end process_status_pipe.last.close unless process_status_pipe.last.closed? exit! end end # Attempt to get a Marshaled error from the side-channel. # If it's there, un-marshal it and raise. If it's not there, # assume everything went well. def propagate_pre_exec_failure attempt_buffer_read until child_process_status.eof? e = Marshal.load(@process_status) raise(Exception === e ? e : "unknown failure: #{e.inspect}") rescue ArgumentError # If we get an ArgumentError error, then the exec was successful true ensure child_process_status.close open_pipes.delete(child_process_status) end def reap_errant_child return if attempt_reap @terminate_reason = "Command exceeded allowed execution time, process terminated" logger&.error("Command exceeded allowed execution time, sending TERM") Process.kill(:TERM, child_pgid) sleep 3 attempt_reap logger&.error("Command exceeded allowed execution time, sending KILL") Process.kill(:KILL, child_pgid) reap # Should not hit this but it's possible if something is calling waitall # in a separate thread. rescue Errno::ESRCH nil end def should_reap? # if we fail to fork, no child pid so nothing to reap @child_pid && !@reaped end # Unconditionally reap the child process. This is used in scenarios where # we can be confident the child will exit quickly, and has not spawned # and grandchild processes. def reap results = Process.waitpid2(@child_pid) @reaped = true @status = results.last rescue Errno::ECHILD # When cleaning up timed-out processes, we might send SIGKILL to the # whole process group after we've cleaned up the direct child. In that # case the grandchildren will have been adopted by init so we can't # reap them even if we wanted to (we don't). nil end # Try to reap the child process but don't block if it isn't dead yet. def attempt_reap results = Process.waitpid2(@child_pid, Process::WNOHANG) if results @reaped = true @status = results.last else nil end end end end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/lib/mixlib/shellout/helper.rb
lib/mixlib/shellout/helper.rb
#-- # Author:: Daniel DeLeo (<dan@chef.io>) # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../shellout" require "chef-utils" unless defined?(ChefUtils) require "chef-utils/dsl/default_paths" require "chef-utils/internal" module Mixlib class ShellOut module Helper include ChefUtils::Internal include ChefUtils::DSL::DefaultPaths # # These APIs are considered public for use in ohai and chef (by cookbooks and plugins, etc) # but are considered private/experimental for now for the direct users of mixlib-shellout. # # You can see an example of how to handle the "dependency injection" in the rspec unit test. # That backend API is left deliberately undocumented for now and may not follow SemVer and may # break at any time (at least for the rest of 2020). # def shell_out(*args, **options) options = options.dup options = __maybe_add_timeout(self, options) if options.empty? shell_out_compacted(*__clean_array(*args)) else shell_out_compacted(*__clean_array(*args), **options) end end def shell_out!(*args, **options) options = options.dup options = __maybe_add_timeout(self, options) if options.empty? shell_out_compacted!(*__clean_array(*args)) else shell_out_compacted!(*__clean_array(*args), **options) end end private # helper sugar for resources that support passing timeouts to shell_out # # module method to not pollute namespaces, but that means we need self injected as an arg # @api private def __maybe_add_timeout(obj, options) options = options.dup # historically resources have not properly declared defaults on their timeouts, so a default default of 900s was enforced here default_val = 900 return options if options.key?(:timeout) # FIXME: need to nuke descendent tracker out of Chef::Provider so we can just define that class here without requiring the # world, and then just use symbol lookup if obj.class.ancestors.map(&:name).include?("Chef::Provider") && obj.respond_to?(:new_resource) && obj.new_resource.respond_to?(:timeout) && !options.key?(:timeout) options[:timeout] = obj.new_resource.timeout ? obj.new_resource.timeout.to_f : default_val end options end # helper function to mangle options when `default_env` is true # # @api private def __apply_default_env(options) options = options.dup default_env = options.delete(:default_env) default_env = true if default_env.nil? if default_env env_key = options.key?(:env) ? :env : :environment options[env_key] = { "LC_ALL" => __config[:internal_locale], "LANGUAGE" => __config[:internal_locale], "LANG" => __config[:internal_locale], __env_path_name => default_paths, }.update(options[env_key] || {}) end options end # The shell_out_compacted/shell_out_compacted! APIs are private but are intended for use # in rspec tests. They should always be used in rspec tests instead of shell_out to allow # for less brittle rspec tests. # # This expectation: # # allow(provider).to receive(:shell_out_compacted!).with("foo", "bar", "baz") # # Is met by many different possible calling conventions that mean the same thing: # # provider.shell_out!("foo", [ "bar", nil, "baz"]) # provider.shell_out!(["foo", nil, "bar" ], ["baz"]) # # Note that when setting `default_env: false` that you should just setup an expectation on # :shell_out_compacted for `default_env: false`, rather than the expanded env settings so # that the default_env implementation can change without breaking unit tests. # def shell_out_compacted(*args, **options) options = __apply_default_env(options) if options.empty? __shell_out_command(*args) else __shell_out_command(*args, **options) end end def shell_out_compacted!(*args, **options) options = __apply_default_env(options) cmd = if options.empty? __shell_out_command(*args) else __shell_out_command(*args, **options) end cmd.error! cmd end # Helper for subclasses to reject nil out of an array. It allows using the array form of # shell_out (which avoids the need to surround arguments with quote marks to deal with shells). # # @param args [String] variable number of string arguments # @return [Array] array of strings with nil and null string rejection # def __clean_array(*args) args.flatten.compact.map(&:to_s) end # Join arguments into a string. # # Strips leading/trailing spaces from each argument. If an argument contains # a space, it is quoted. Join into a single string with spaces between each argument. # # @param args [String] variable number of string arguments # @return [String] merged string # def __join_whitespace(*args, quote: false) args.map do |arg| if arg.is_a?(Array) __join_whitespace(*arg, quote: arg.count > 1) else arg = arg.include?(" ") ? sprintf('"%s"', arg) : arg if quote arg.strip end end.join(" ") end def __shell_out_command(*args, **options) if __transport_connection command = __join_whitespace(args) unless ChefUtils.windows? if options[:cwd] # as `timeout` is used, commands need to be executed in a subshell command = "sh -c 'cd #{options[:cwd]}; #{command}'" end if options[:input] command.concat "<<'COMMANDINPUT'\n" command.concat __join_whitespace(options[:input]) command.concat "\nCOMMANDINPUT\n" end end # FIXME: train should accept run_command(*args) FakeShellOut.new(args, options, __transport_connection.run_command(command, options)) else cmd = if options.empty? Mixlib::ShellOut.new(*args) else Mixlib::ShellOut.new(*args, **options) end cmd.live_stream ||= __io_for_live_stream cmd.run_command cmd end end def __io_for_live_stream if !STDOUT.closed? && __log.trace? STDOUT else nil end end def __env_path_name if ChefUtils.windows? "Path" else "PATH" end end class FakeShellOut attr_reader :stdout, :stderr, :exitstatus, :status def initialize(args, options, result) @args = args @options = options @stdout = result.stdout @stderr = result.stderr @exitstatus = result.exit_status @valid_exit_codes = Array(options[:returns] || 0) @status = OpenStruct.new(success?: (@valid_exit_codes.include? exitstatus)) end def error? @valid_exit_codes.none?(exitstatus) end def error! raise Mixlib::ShellOut::ShellCommandFailed, "Unexpected exit status of #{exitstatus} running #{@args}: #{stderr}" if error? end end end end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/lib/mixlib/shellout/windows.rb
lib/mixlib/shellout/windows.rb
# # frozen_string_literal: true # Author:: Daniel DeLeo (<dan@chef.io>) # Author:: John Keiser (<jkeiser@chef.io>) # Author:: Ho-Sheng Hsiao (<hosh@chef.io>) # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "win32/process" require_relative "windows/core_ext" module Mixlib class ShellOut module Windows include Process::Functions include Process::Constants TIME_SLICE = 0.05 # Option validation that is windows specific def validate_options(opts) if opts[:user] && !opts[:password] raise InvalidCommandOption, "You must supply a password when supplying a user in windows" end if !opts[:user] && opts[:password] raise InvalidCommandOption, "You must supply a user when supplying a password in windows" end if opts[:elevated] && !opts[:user] && !opts[:password] raise InvalidCommandOption, "`elevated` option should be passed only with `username` and `password`." end return unless opts[:elevated] && opts[:elevated] != true && opts[:elevated] != false raise InvalidCommandOption, "Invalid value passed for `elevated`. Please provide true/false." end #-- # Missing lots of features from the UNIX version, such as # uid, etc. def run_command # # Create pipes to capture stdout and stderr, # stdout_read, stdout_write = IO.pipe stderr_read, stderr_write = IO.pipe stdin_read, stdin_write = IO.pipe open_streams = [stdout_read, stderr_read] @execution_time = 0 begin # # Set cwd, environment, appname, etc. # app_name, command_line = command_to_run(combine_args(*command)) create_process_args = { app_name:, command_line:, startup_info: { stdout: stdout_write, stderr: stderr_write, stdin: stdin_read, }, environment: inherit_environment.map { |k, v| "#{k}=#{v}" }, close_handles: false, } create_process_args[:cwd] = cwd if cwd # default to local account database if domain is not specified create_process_args[:domain] = domain.nil? ? "." : domain create_process_args[:with_logon] = with_logon if with_logon create_process_args[:password] = password if password create_process_args[:elevated] = elevated if elevated # # Start the process # process, profile, token = Process.create3(create_process_args) logger&.debug(format_process(process, app_name, command_line, timeout)) begin # Start pushing data into input stdin_write << input if input # Close pipe to kick things off stdin_write.close # # Wait for the process to finish, consuming output as we go # start_wait = Time.now loop do wait_status = WaitForSingleObject(process.process_handle, 0) case wait_status when WAIT_OBJECT_0 # Save the execution time @execution_time = Time.now - start_wait # Get process exit code exit_code = [0].pack("l") raise get_last_error unless GetExitCodeProcess(process.process_handle, exit_code) @status = ThingThatLooksSortOfLikeAProcessStatus.new @status.exitstatus = exit_code.unpack1("l") return self when WAIT_TIMEOUT # Kill the process if (Time.now - start_wait) > timeout begin require "wmi-lite/wmi" wmi = WmiLite::Wmi.new kill_process_tree(process.process_id, wmi, logger) Process.kill(:KILL, process.process_id) rescue SystemCallError logger&.warn("Failed to kill timed out process #{process.process_id}") end # Save the execution time @execution_time = Time.now - start_wait raise Mixlib::ShellOut::CommandTimeout, [ "command timed out:", format_for_exception, format_process(process, app_name, command_line, timeout), ].join("\n") end consume_output(open_streams, stdout_read, stderr_read) else raise "Unknown response from WaitForSingleObject(#{process.process_handle}, #{timeout * 1000}): #{wait_status}" end end ensure CloseHandle(process.thread_handle) if process.thread_handle CloseHandle(process.process_handle) if process.process_handle Process.unload_user_profile(token, profile) if profile CloseHandle(token) if token end ensure # # Consume all remaining data from the pipes until they are closed # stdout_write.close stderr_write.close while consume_output(open_streams, stdout_read, stderr_read) end end end class ThingThatLooksSortOfLikeAProcessStatus attr_accessor :exitstatus def success? exitstatus == 0 end end private def consume_output(open_streams, stdout_read, stderr_read) return false if open_streams.length == 0 ready = IO.select(open_streams, nil, nil, READ_WAIT_TIME) return true unless ready if ready.first.include?(stdout_read) begin # The unary plus operator (+) creates a mutable copy of the string returned by readpartial. # This is necessary because readpartial may return a frozen string, and we need to be able # to modify the string (append to buffers, manipulate encoding, etc.) in subsequent operations. # Without the +, attempting to modify a frozen string would raise a FrozenError. next_chunk = +stdout_read.readpartial(READ_SIZE) @stdout << next_chunk @live_stdout << next_chunk if @live_stdout rescue EOFError stdout_read.close open_streams.delete(stdout_read) end end if ready.first.include?(stderr_read) begin next_chunk = +stderr_read.readpartial(READ_SIZE) @stderr << next_chunk @live_stderr << next_chunk if @live_stderr rescue EOFError stderr_read.close open_streams.delete(stderr_read) end end true end # Use to support array passing semantics on windows # # 1. strings with whitespace or quotes in them need quotes around them. # 2. interior quotes need to get backslash escaped (parser needs to know when it really ends). # 3. random backlsashes in paths themselves remain untouched. # 4. if the argument must be quoted by #1 and terminates in a sequence of backslashes then all the backlashes must themselves # be backslash excaped (double the backslashes). # 5. if an interior quote that must be escaped by #2 has a sequence of backslashes before it then all the backslashes must # themselves be backslash excaped along with the backslash escape of the interior quote (double plus one backslashes). # # And to restate. We are constructing a string which will be parsed by the windows parser into arguments, and we want those # arguments to match the *args array we are passed here. So call the windows parser operation A then we need to apply A^-1 to # our args to construct the string so that applying A gives windows back our *args. # # And when the windows parser sees a series of backslashes followed by a double quote, it has to determine if that double quote # is terminating or not, and how many backslashes to insert in the args. So what it does is divide it by two (rounding down) to # get the number of backslashes to insert. Then if it is even the double quotes terminate the argument. If it is even the # double quotes are interior double quotes (the extra backslash quotes the double quote). # # We construct the inverse operation so interior double quotes preceeded by N backslashes get 2N+1 backslashes in front of the quote, # while trailing N backslashes get 2N backslashes in front of the quote that terminates the argument. # # see: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ # # @api private # @param args [Array<String>] array of command arguments # @return String def combine_args(*args) return args[0] if args.length == 1 args.map do |arg| if arg =~ /[ \t\n\v"]/ arg = arg.gsub(/(\\*)"/, '\1\1\"') # interior quotes with N preceeding backslashes need 2N+1 backslashes arg = arg.sub(/(\\+)$/, '\1\1') # trailing N backslashes need to become 2N backslashes "\"#{arg}\"" else arg end end.join(" ") end def command_to_run(command) return run_under_cmd(command) if should_run_under_cmd?(command) candidate = candidate_executable_for_command(command) if candidate.length == 0 raise Mixlib::ShellOut::EmptyWindowsCommand, "could not parse script/executable out of command: `#{command}`" end # Check if the exe exists directly. Otherwise, search PATH. exe = which(candidate) if exe_needs_cmd?(exe) run_under_cmd(command) else [exe, command] end end # Batch files MUST use cmd; and if we couldn't find the command we're looking for, # we assume it must be a cmd builtin. def exe_needs_cmd?(exe) !exe || exe =~ /\.bat"?$|\.cmd"?$/i end # cmd does not parse multiple quotes well unless the whole thing is wrapped up in quotes. # https://github.com/chef/mixlib-shellout/pull/2#issuecomment-4837859 # http://ss64.com/nt/syntax-esc.html def run_under_cmd(command) [ENV["COMSPEC"], "cmd /c \"#{command}\""] end # FIXME: this extracts ARGV[0] but is it correct? def candidate_executable_for_command(command) if command =~ /^\s*"(.*?)"/ || command =~ /^\s*([^\s]+)/ # If we have quotes, do an exact match, else pick the first word ignoring the leading spaces ::Regexp.last_match(1) else "" end end def inherit_environment result = {} ENV.each_pair do |k, v| result[k] = v end environment.each_pair do |k, v| if v.nil? result.delete(k) else result[k] = v end end result end # api: semi-private # If there are special characters parsable by cmd.exe (such as file redirection), then # this method should return true. # # This parser is based on # https://github.com/ruby/ruby/blob/9073db5cb1d3173aff62be5b48d00f0fb2890991/win32/win32.c#L1437 def should_run_under_cmd?(command) return true if command =~ /^@/ quote = nil env = false env_first_char = false command.dup.each_char do |c| case c when "'", '"' if !quote quote = c elsif quote == c quote = nil end next when ">", "<", "|", "&", "\n" return true unless quote when "%" return true if env env = env_first_char = true next else next unless env if env_first_char env_first_char = false (env = false) && next if c !~ /[A-Za-z_]/ end env = false if c !~ /[A-Za-z1-9_]/ end end false end # FIXME: reduce code duplication with chef/chef def which(cmd) exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(";") + [""] : [""] # windows always searches '.' first exts.each do |ext| filename = "#{cmd}#{ext}" return filename if File.executable?(filename) && !File.directory?(filename) end # only search through the path if the Filename does not contain separators if File.basename(cmd) == cmd paths = ENV["PATH"].split(File::PATH_SEPARATOR) paths.each do |path| exts.each do |ext| filename = File.join(path, "#{cmd}#{ext}") return filename if File.executable?(filename) && !File.directory?(filename) end end end false end def system_required_processes [ "System Idle Process", "System", "spoolsv.exe", "lsass.exe", "csrss.exe", "smss.exe", "svchost.exe", ] end def unsafe_process?(name, logger) return false unless system_required_processes.include? name logger.debug( "A request to kill a critical system process - #{name} - was received and skipped." ) true end # recursively kills all child processes of given pid # calls itself querying for children child procs until # none remain. Important that a single WmiLite instance # is passed in since each creates its own WMI rpc process def kill_process_tree(pid, wmi, logger) wmi.query("select * from Win32_Process where ParentProcessID=#{pid}").each do |instance| next if unsafe_process?(instance.wmi_ole_object.name, logger) child_pid = instance.wmi_ole_object.processid kill_process_tree(child_pid, wmi, logger) kill_process(instance, logger) end end def kill_process(instance, logger) child_pid = instance.wmi_ole_object.processid logger&.debug([ "killing child process #{child_pid}::", "#{instance.wmi_ole_object.Name} of parent #{pid}", ].join) Process.kill(:KILL, instance.wmi_ole_object.processid) rescue SystemCallError logger&.debug([ "Failed to kill child process #{child_pid}::", "#{instance.wmi_ole_object.Name} of parent #{pid}", ].join) end def format_process(process, app_name, command_line, timeout) msg = [] msg << "ProcessId: #{process.process_id}" msg << "app_name: #{app_name}" msg << "command_line: #{command_line}" msg << "timeout: #{timeout}" msg.join("\n") end # DEPRECATED do not use class Utils include Mixlib::ShellOut::Windows def self.should_run_under_cmd?(cmd) Mixlib::ShellOut::Windows::Utils.new.send(:should_run_under_cmd?, cmd) end end end end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/lib/mixlib/shellout/windows/core_ext.rb
lib/mixlib/shellout/windows/core_ext.rb
# # Author:: Daniel DeLeo (<dan@chef.io>) # Author:: John Keiser (<jkeiser@chef.io>) # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "win32/process" require "ffi/win32/extensions" # Add new constants for Logon module Process::Constants LOGON32_LOGON_INTERACTIVE = 0x00000002 LOGON32_LOGON_BATCH = 0x00000004 LOGON32_PROVIDER_DEFAULT = 0x00000000 UOI_NAME = 0x00000002 WAIT_OBJECT_0 = 0 WAIT_TIMEOUT = 0x102 WAIT_ABANDONED = 128 WAIT_ABANDONED_0 = WAIT_ABANDONED WAIT_FAILED = 0xFFFFFFFF ERROR_PRIVILEGE_NOT_HELD = 1314 ERROR_LOGON_TYPE_NOT_GRANTED = 0x569 # Only documented in Userenv.h ??? # - ZERO (type Local) is assumed, no docs found WIN32_PROFILETYPE_LOCAL = 0x00 WIN32_PROFILETYPE_PT_TEMPORARY = 0x01 WIN32_PROFILETYPE_PT_ROAMING = 0x02 WIN32_PROFILETYPE_PT_MANDATORY = 0x04 WIN32_PROFILETYPE_PT_ROAMING_PREEXISTING = 0x08 # The environment block list ends with two nulls (\0\0). ENVIRONMENT_BLOCK_ENDS = "\0\0".freeze end # Structs required for data handling module Process::Structs class PROFILEINFO < FFI::Struct layout( :dwSize, :dword, :dwFlags, :dword, :lpUserName, :pointer, :lpProfilePath, :pointer, :lpDefaultPath, :pointer, :lpServerName, :pointer, :lpPolicyPath, :pointer, :hProfile, :handle ) end end # Define the functions needed to check with Service windows station module Process::Functions ffi_lib :userenv attach_pfunc :GetProfileType, [:pointer], :bool attach_pfunc :LoadUserProfileW, %i{handle pointer}, :bool attach_pfunc :UnloadUserProfile, %i{handle handle}, :bool attach_pfunc :CreateEnvironmentBlock, %i{pointer ulong bool}, :bool attach_pfunc :DestroyEnvironmentBlock, %i{pointer}, :bool ffi_lib :advapi32 attach_pfunc :LogonUserW, %i{buffer_in buffer_in buffer_in ulong ulong pointer}, :bool attach_pfunc :CreateProcessAsUserW, %i{ulong buffer_in buffer_inout pointer pointer int ulong buffer_in buffer_in pointer pointer}, :bool ffi_lib :user32 attach_pfunc :GetProcessWindowStation, [], :ulong attach_pfunc :GetUserObjectInformationA, %i{ulong uint buffer_out ulong pointer}, :bool end # Override Process.create to check for running in the Service window station and doing # a full logon with LogonUser, instead of a CreateProcessWithLogon # Cloned from https://github.com/djberg96/win32-process/blob/ffi/lib/win32/process.rb # as of 2015-10-15 from commit cc066e5df25048f9806a610f54bf5f7f253e86f7 module Process class UnsupportedFeature < StandardError; end # Explicitly reopen singleton class so that class/constant declarations from # extensions are visible in Modules.nesting. class << self def create(args) create3(args).first end def create3(args) unless args.is_a?(Hash) raise TypeError, "hash keyword arguments expected" end valid_keys = %w{ app_name command_line inherit creation_flags cwd environment startup_info thread_inherit process_inherit close_handles with_logon domain password elevated } valid_si_keys = %w{ startf_flags desktop title x y x_size y_size x_count_chars y_count_chars fill_attribute sw_flags stdin stdout stderr } # Set default values hash = { "app_name" => nil, "creation_flags" => 0, "close_handles" => true, } # Validate the keys, and convert symbols and case to lowercase strings. args.each do |key, val| key = key.to_s.downcase unless valid_keys.include?(key) raise ArgumentError, "invalid key '#{key}'" end hash[key] = val end si_hash = {} # If the startup_info key is present, validate its subkeys hash["startup_info"]&.each do |key, val| key = key.to_s.downcase unless valid_si_keys.include?(key) raise ArgumentError, "invalid startup_info key '#{key}'" end si_hash[key] = val end # The +command_line+ key is mandatory unless the +app_name+ key # is specified. unless hash["command_line"] if hash["app_name"] hash["command_line"] = hash["app_name"] hash["app_name"] = nil else raise ArgumentError, "command_line or app_name must be specified" end end env = nil # Retrieve the environment variables for the specified user. if hash["with_logon"] logon, passwd, domain = format_creds_from_hash(hash) logon_type = hash["elevated"] ? LOGON32_LOGON_BATCH : LOGON32_LOGON_INTERACTIVE token = logon_user(logon, domain, passwd, logon_type) logon_ptr = FFI::MemoryPointer.from_string(logon) profile = PROFILEINFO.new.tap do |dat| dat[:dwSize] = dat.size dat[:dwFlags] = 1 dat[:lpUserName] = logon_ptr end load_user_profile(token, profile.pointer) env_list = retrieve_environment_variables(token) end # The env string should be passed as a string of ';' separated paths. if hash["environment"] env = env_list.nil? ? hash["environment"] : merge_env_variables(env_list, hash["environment"]) unless env.respond_to?(:join) env = hash["environment"].split(File::PATH_SEPARATOR) end env = env.map { |e| e + 0.chr }.join("") + 0.chr env.to_wide_string! if hash["with_logon"] end # Process SECURITY_ATTRIBUTE structure process_security = nil if hash["process_inherit"] process_security = SECURITY_ATTRIBUTES.new process_security[:nLength] = 12 process_security[:bInheritHandle] = 1 end # Thread SECURITY_ATTRIBUTE structure thread_security = nil if hash["thread_inherit"] thread_security = SECURITY_ATTRIBUTES.new thread_security[:nLength] = 12 thread_security[:bInheritHandle] = 1 end # Automatically handle stdin, stdout and stderr as either IO objects # or file descriptors. This won't work for StringIO, however. It also # will not work on JRuby because of the way it handles internal file # descriptors. # %w{stdin stdout stderr}.each do |io| if si_hash[io] if si_hash[io].respond_to?(:fileno) handle = get_osfhandle(si_hash[io].fileno) else handle = get_osfhandle(si_hash[io]) end if handle == INVALID_HANDLE_VALUE ptr = FFI::MemoryPointer.new(:int) if windows_version >= 6 && get_errno(ptr) == 0 errno = ptr.read_int else errno = FFI.errno end raise SystemCallError.new("get_osfhandle", errno) end # Most implementations of Ruby on Windows create inheritable # handles by default, but some do not. RF bug #26988. bool = SetHandleInformation( handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT ) raise SystemCallError.new("SetHandleInformation", FFI.errno) unless bool si_hash[io] = handle si_hash["startf_flags"] ||= 0 si_hash["startf_flags"] |= STARTF_USESTDHANDLES hash["inherit"] = true end end procinfo = PROCESS_INFORMATION.new startinfo = STARTUPINFO.new unless si_hash.empty? startinfo[:cb] = startinfo.size startinfo[:lpDesktop] = si_hash["desktop"] if si_hash["desktop"] startinfo[:lpTitle] = si_hash["title"] if si_hash["title"] startinfo[:dwX] = si_hash["x"] if si_hash["x"] startinfo[:dwY] = si_hash["y"] if si_hash["y"] startinfo[:dwXSize] = si_hash["x_size"] if si_hash["x_size"] startinfo[:dwYSize] = si_hash["y_size"] if si_hash["y_size"] startinfo[:dwXCountChars] = si_hash["x_count_chars"] if si_hash["x_count_chars"] startinfo[:dwYCountChars] = si_hash["y_count_chars"] if si_hash["y_count_chars"] startinfo[:dwFillAttribute] = si_hash["fill_attribute"] if si_hash["fill_attribute"] startinfo[:dwFlags] = si_hash["startf_flags"] if si_hash["startf_flags"] startinfo[:wShowWindow] = si_hash["sw_flags"] if si_hash["sw_flags"] startinfo[:cbReserved2] = 0 startinfo[:hStdInput] = si_hash["stdin"] if si_hash["stdin"] startinfo[:hStdOutput] = si_hash["stdout"] if si_hash["stdout"] startinfo[:hStdError] = si_hash["stderr"] if si_hash["stderr"] end app = nil cmd = nil # Convert strings to wide character strings if present if hash["app_name"] app = hash["app_name"].to_wide_string end if hash["command_line"] cmd = hash["command_line"].to_wide_string end if hash["cwd"] cwd = hash["cwd"].to_wide_string end inherit = hash["inherit"] ? 1 : 0 if hash["with_logon"] logon, passwd, domain = format_creds_from_hash(hash) hash["creation_flags"] |= CREATE_UNICODE_ENVIRONMENT winsta_name = get_windows_station_name # If running in the service windows station must do a log on to get # to the interactive desktop. The running process user account must have # the 'Replace a process level token' permission. This is necessary as # the logon (which happens with CreateProcessWithLogon) must have an # interactive windows station to attach to, which is created with the # LogonUser call with the LOGON32_LOGON_INTERACTIVE flag. # # User Access Control (UAC) only applies to interactive logons, so we # can simulate running a command 'elevated' by running it under a separate # logon as a batch process. if hash["elevated"] || winsta_name =~ /^Service-0x0-.*$/i logon_type = hash["elevated"] ? LOGON32_LOGON_BATCH : LOGON32_LOGON_INTERACTIVE token = logon_user(logon, domain, passwd, logon_type) logon_ptr = FFI::MemoryPointer.from_string(logon) profile = PROFILEINFO.new.tap do |dat| dat[:dwSize] = dat.size dat[:dwFlags] = 1 dat[:lpUserName] = logon_ptr end if logon_has_roaming_profile? msg = %w{ Mixlib does not currently support executing commands as users configured with Roaming Profiles. [%s] }.join(" ") % logon.encode("UTF-8").unpack("A*") raise UnsupportedFeature.new(msg) end load_user_profile(token, profile.pointer) create_process_as_user(token, app, cmd, process_security, thread_security, inherit, hash["creation_flags"], env, cwd, startinfo, procinfo) else create_process_with_logon(logon, domain, passwd, LOGON_WITH_PROFILE, app, cmd, hash["creation_flags"], env, cwd, startinfo, procinfo) end else create_process(app, cmd, process_security, thread_security, inherit, hash["creation_flags"], env, cwd, startinfo, procinfo) end # Automatically close the process and thread handles in the # PROCESS_INFORMATION struct unless explicitly told not to. if hash["close_handles"] CloseHandle(procinfo[:hProcess]) CloseHandle(procinfo[:hThread]) # Clear these fields so callers don't attempt to close the handle # which can result in the wrong handle being closed or an # exception in some circumstances. procinfo[:hProcess] = 0 procinfo[:hThread] = 0 end process = ProcessInfo.new( procinfo[:hProcess], procinfo[:hThread], procinfo[:dwProcessId], procinfo[:dwThreadId] ) [ process, profile, token ] end # See Process::Constants::WIN32_PROFILETYPE def logon_has_roaming_profile? get_profile_type >= 2 end def get_profile_type ptr = FFI::MemoryPointer.new(:uint) unless GetProfileType(ptr) raise SystemCallError.new("GetProfileType", FFI.errno) end ptr.read_uint end def load_user_profile(token, profile_ptr) unless LoadUserProfileW(token, profile_ptr) raise SystemCallError.new("LoadUserProfileW", FFI.errno) end true end def unload_user_profile(token, profile) if profile[:hProfile] == 0 warn "\n\nWARNING: Profile not loaded\n" else unless UnloadUserProfile(token, profile[:hProfile]) raise SystemCallError.new("UnloadUserProfile", FFI.errno) end end true end # Retrieves the environment variables for the specified user. # # @param env_pointer [Pointer] The environment block is an array of null-terminated Unicode strings. # @param token [Integer] User token handle. # @return [Boolean] true if successfully retrieves the environment variables for the specified user. # def create_environment_block(env_pointer, token) unless CreateEnvironmentBlock(env_pointer, token, false) raise SystemCallError.new("CreateEnvironmentBlock", FFI.errno) end true end # Frees environment variables created by the CreateEnvironmentBlock function. # # @param env_pointer [Pointer] The environment block is an array of null-terminated Unicode strings. # @return [Boolean] true if successfully frees environment variables created by the CreateEnvironmentBlock function. # def destroy_environment_block(env_pointer) unless DestroyEnvironmentBlock(env_pointer) raise SystemCallError.new("DestroyEnvironmentBlock", FFI.errno) end true end def create_process_as_user(token, app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo) bool = CreateProcessAsUserW( token, # User token handle app, # App name cmd, # Command line process_security, # Process attributes thread_security, # Thread attributes inherit, # Inherit handles creation_flags, # Creation Flags env, # Environment cwd, # Working directory startinfo, # Startup Info procinfo # Process Info ) unless bool msg = case FFI.errno when ERROR_PRIVILEGE_NOT_HELD [ %{CreateProcessAsUserW (User '%s' must hold the 'Replace a process}, %{level token' and 'Adjust Memory Quotas for a process' permissions.}, %{Logoff the user after adding this right to make it effective.)}, ].join(" ") % ::ENV["USERNAME"] else "CreateProcessAsUserW failed." end raise SystemCallError.new(msg, FFI.errno) end end def create_process_with_logon(logon, domain, passwd, logon_flags, app, cmd, creation_flags, env, cwd, startinfo, procinfo) bool = CreateProcessWithLogonW( logon, # User domain, # Domain passwd, # Password logon_flags, # Logon flags app, # App name cmd, # Command line creation_flags, # Creation flags env, # Environment cwd, # Working directory startinfo, # Startup Info procinfo # Process Info ) unless bool raise SystemCallError.new("CreateProcessWithLogonW", FFI.errno) end end def create_process(app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo) bool = CreateProcessW( app, # App name cmd, # Command line process_security, # Process attributes thread_security, # Thread attributes inherit, # Inherit handles? creation_flags, # Creation flags env, # Environment cwd, # Working directory startinfo, # Startup Info procinfo # Process Info ) unless bool raise SystemCallError.new("CreateProcessW", FFI.errno) end end def logon_user(user, domain, passwd, type, provider = LOGON32_PROVIDER_DEFAULT) token = FFI::MemoryPointer.new(:ulong) bool = LogonUserW( user, # User domain, # Domain passwd, # Password type, # Logon Type provider, # Logon Provider token # User token handle ) unless bool if (FFI.errno == ERROR_LOGON_TYPE_NOT_GRANTED) && (type == LOGON32_LOGON_BATCH) user_utf8 = user.encode( "UTF-8", invalid: :replace, undef: :replace, replace: "" ).delete("\0") raise SystemCallError.new("LogonUserW (User '#{user_utf8}' must hold 'Log on as a batch job' permissions.)", FFI.errno) else raise SystemCallError.new("LogonUserW", FFI.errno) end end token.read_ulong end def get_windows_station_name winsta_name = FFI::MemoryPointer.new(:char, 256) return_size = FFI::MemoryPointer.new(:ulong) bool = GetUserObjectInformationA( GetProcessWindowStation(), # Window station handle UOI_NAME, # Information to get winsta_name, # Buffer to receive information winsta_name.size, # Size of buffer return_size # Size filled into buffer ) unless bool raise SystemCallError.new("GetUserObjectInformationA", FFI.errno) end winsta_name.read_string(return_size.read_ulong) end def format_creds_from_hash(hash) logon = hash["with_logon"].to_wide_string if hash["password"] passwd = hash["password"].to_wide_string else raise ArgumentError, "password must be specified if with_logon is used" end if hash["domain"] domain = hash["domain"].to_wide_string end [ logon, passwd, domain ] end # Retrieves the environment variables for the specified user. # # @param token [Integer] User token handle. # @return env_list [Array<String>] Environment variables of specified user. # def retrieve_environment_variables(token) env_list = [] env_pointer = FFI::MemoryPointer.new(:pointer) create_environment_block(env_pointer, token) str_ptr = env_pointer.read_pointer offset = 0 loop do new_str_pointer = str_ptr + offset break if new_str_pointer.read_string(2) == ENVIRONMENT_BLOCK_ENDS environment = new_str_pointer.read_wstring env_list << environment offset = offset + environment.length * 2 + 2 end # To free the buffer when we have finished with the environment block destroy_environment_block(str_ptr) env_list end # Merge environment variables of specified user and current environment variables. # # @param fetched_env [Array<String>] environment variables of specified user. # @param current_env [Array<String>] current environment variables. # @return [Array<String>] Merged environment variables. # def merge_env_variables(fetched_env, current_env) env_hash_1 = environment_list_to_hash(fetched_env) env_hash_2 = environment_list_to_hash(current_env) merged_env = env_hash_2.merge(env_hash_1) merged_env.map { |k, v| "#{k}=#{v}" } end # Convert an array to a hash. # # @param env_var [Array<String>] Environment variables. # @return [Hash] Converted an array to hash. # def environment_list_to_hash(env_var) Hash[ env_var.map { |pair| pair.split("=", 2) } ] end end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/uninstall.rb
uninstall.rb
# Uninstall hook code here
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/install.rb
install.rb
# Install hook code here
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/init.rb
init.rb
require 'smerf'
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/helpers/smerf_test.rb
app/helpers/smerf_test.rb
module SmerfTestHelper end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/helpers/smerf_forms_helper.rb
app/helpers/smerf_forms_helper.rb
require "smerf_system_helpers" # This module contains all the helper methods used by the smerf form views. module SmerfFormsHelper include SmerfSystemHelpers # This method creates a formatted error message that is then # displayed on the smerf form page to inform the user of any errors. # # CSS identifier: <tt>smerfFormError</tt> # def get_error_messages(errors) if (errors and !errors.empty?()) header_message = "#{pluralize(errors.size(), 'error')} prevented #{@smerfform.name} from being saved" error_messages = "" errors.each do |error| # Check if question text available as some questions may have no text, # e.g. sub questions. If this happens we check all parent objects to see # if the question text is available until text found or no more parents question = (error[1]["question"] and !error[1]["question"].blank?()) ? error[1]["question"] : find_question_text(error[0]) # Format error message error[1]["msg"].each do |error_msg| error_messages += content_tag(:li, "#{question}: #{error_msg}") end end content_tag(:div, content_tag(:h2, raw(header_message)) << content_tag(:p, 'There were problems with the following questions:') << content_tag(:ul, raw(error_messages)), :class => "smerfFormError") else '' end end # This method creates a formatted notice message that is then # displayed on the smerf form. The notice message is retrieved # from the flash[:notice]. # # CSS identifier: <tt>smerfFormNotice</tt> # def get_notice_messages if flash[:notice] content_tag(:div, content_tag(:p, flash[:notice]), :class => "smerfFormNotice") end end # This method retrieves and formats the form title. # # CSS identifier: <tt>h2</tt> # def smerf_title if !@smerfform.form.name.blank? content_tag(:h2, raw(@smerfform.form.name)) end end # This method retrieves and formats the form welcome message. # # CSS identifier: <tt>formWelcome</tt> # def smerf_welcome if !@smerfform.form.welcome.blank? content_tag(:div, content_tag(:p, raw(@smerfform.form.welcome)), :class => "smerfWelcome") end end # This method retrieves and formats the form thank you message. # # CSS identifier: <tt>smerfThankyou</tt> # def smerf_thank_you if !@smerfform.form.thank_you.blank? content_tag(:div, content_tag(:p, raw(@smerfform.form.thank_you)), :class => "smerfThankyou") end end # This method retrieves and formats the group name of the group # passed in as a parameter. # # CSS identifier: <tt>smerfGroup</tt> # def smerf_group_name(group) if !group.name.blank? content_tag(:div, content_tag(:h3, raw(group.name)), :class => "smerfGroup") end end # This method retrieves and formats the group description of the group # passed in as a parameter. # # CSS identifier: <tt>smerfGroup</tt> # def smerf_group_description(group) if !group.description.blank? content_tag(:div, content_tag(:p, raw(group.description)), :class => "smerfGroupDescription") end end # This method retrieves all the groups defined in the form. # def smerf_get_groups @smerfform.form.groups end # This method retrieves all the questions defined for the group # passed in as a parameter. # def smerf_get_group_questions(group) group.questions end # This method formats the question, and any answers and subquestions # defined for it. The method takes a question object(SmerfQuestion) # and a level indicator as parameters. The level indicator tells us if # a question is a subquestion or not (level > 1). # # The question type is checked to see how is should be formatted, currently # the following formats are supported: # # * Multiple choice (checkbox) # * Single choice (radio) # * Text field (large amount of text) # * Text box (small amount of text) # # CSS identifiers: # smerfQuestionHeader # smerfQuestion # smerfSubquestion # smerfQuestionError # smerfInstruction # def smerf_group_question(question, level = 1) contents = "" # Format question header contents += content_tag(:div, content_tag(:p, raw(question.header)), {:class => "smerfQuestionHeader"}, false) if (question.header and !question.header.blank?) # Format question contents += content_tag(:div, content_tag(:p, raw(question.question)), {:class => (level <= 1) ? "smerfQuestion" : "smerfSubquestion"}, false) if (question.question and !question.question.blank?) # Format error contents += content_tag(:div, content_tag(:p, raw("#{image_tag("smerf_error.gif", :alt => "Error")} #{@errors["#{question.item_id}"]["msg"]}")), {:class => "smerfQuestionError"}, false) if (@errors and @errors.has_key?("#{question.item_id}")) # Format help contents += content_tag(:div, content_tag(:p, raw("#{image_tag("smerf_help.gif", :alt => "Help")} #{question.help}")), {:class => "smerfInstruction"}, false) if (!question.help.blank?) # Check the type and format appropriatly case question.type when 'multiplechoice' contents += get_multiplechoice(question, level) when 'textbox' contents += get_textbox(question) when 'textfield' contents += get_textfield(question) when 'singlechoice' contents += get_singlechoice(question, level) when 'selectionbox' contents += get_selectionbox(question, level) else raise("Unknown question type for question: #{question.question}") end # Draw a line to indicate the end of the question if level 1, # i.e. not an answer sub question contents += content_tag(:div, "", {:class => "questionbox"}, false) if (!contents.blank? and level <= 1) return contents end private # Some answers to questions may have further questions, here we # process these sub questions. # def process_sub_questions(answer, level) # Process any answer sub quesions by recursivly calling this function sq_contents = "" if (answer.respond_to?("subquestions") and answer.subquestions and answer.subquestions.size > 0) answer.subquestions.each {|subquestion| sq_contents += smerf_group_question(subquestion, level+1)} # Indent question sq_contents = "<div style=\"margin-left: #{level * 25}px;\">" + sq_contents + '</div>' end return sq_contents end # Format multiple choice question # def get_multiplechoice(question, level) contents = "" question.answers.each do |answer| # Get the user input if available user_answer = nil if (@responses and !@responses.empty?() and @responses.has_key?("#{question.code}") and @responses["#{question.code}"].has_key?("#{answer.code}")) user_answer = @responses["#{question.code}"]["#{answer.code}"] end # Note we wrap the form element in a label element, this allows the input # field to be selected by selecting the label, we could otherwise use a # <lable for="....">...</label> construct to do the same html = '<label>' + check_box_tag("responses[#{question.code}][#{answer.code}]", answer.code, # If user responded to the question and the value is the same as the question # value then tick this checkbox ((user_answer and !user_answer.blank?() and user_answer.to_s() == answer.code.to_s()) or # If this is a new record and no responses have been entered, i.e. this is the # first time the new record form is displayed set on if default ((!@responses or @responses.empty?()) and params['action'] == 'show' and answer.default.upcase == 'Y'))) + "#{answer.answer}</label>\n" contents += content_tag(:div, content_tag(:p, raw(html)), :class => "checkbox") # Process any sub questions this answer may have contents += process_sub_questions(answer, level) end # Process error messages if they exist #wrap_error(contents, (@errors and @errors.has_key?("#{question.code}"))) #contents = content_tag(:div, contents, :class => "questionWithErrors") if (@errors and @errors.has_key?("#{question.code}")) return contents end # Format text box question # def get_textbox(question) # Get the user input if available user_answer = nil if (@responses and !@responses.empty?() and @responses.has_key?("#{question.code}")) user_answer = @responses["#{question.code}"] end contents = text_area_tag("responses[#{question.code}]", # Set value to user response if available if (user_answer and !user_answer.blank?()) user_answer else nil end, :size => (!question.textbox_size.blank?) ? question.textbox_size : "30x5") contents = content_tag(:div, content_tag(:p, raw(contents)), :class => "textarea") end # Format text field question # def get_textfield(question) # Get the user input if available user_answer = nil if (@responses and !@responses.empty?() and @responses.has_key?("#{question.code}")) user_answer = @responses["#{question.code}"] end contents = text_field_tag("responses[#{question.code}]", # Set value to user responses if available if (user_answer and !user_answer.blank?()) user_answer else nil end, :size => (!question.textfield_size.blank?) ? question.textfield_size : "30") contents = content_tag(:div, content_tag(:p, raw(contents)), :class => "text") end # Format single choice question # def get_singlechoice(question, level) contents = "" question.answers.each do |answer| # Get the user input_objects if available user_answer = nil if (@responses and !@responses.empty?() and @responses.has_key?("#{question.code}")) user_answer = @responses["#{question.code}"] end # Note we wrap the form element in a label element, this allows the input # field to be selected by selecting the label, we could otherwise use a # <lable for="....">...</label> construct to do the same html = '<label>' + radio_button_tag("responses[#{question.code}]", answer.code, # If user responses then set on if answer available ((user_answer and !user_answer.blank?() and user_answer.to_s() == answer.code.to_s()) or # If this is a new record and no response have been entered, i.e. this is the # first time the new record form is displayed set on if default ((!@responses or @responses.empty?()) and params['action'] == 'show' and answer.default.upcase == 'Y'))) + "#{answer.answer}</label>\n" contents += content_tag(:div, content_tag(:p, raw(html)), :class => "radiobutton") # Process any sub questions this answer may have contents += process_sub_questions(answer, level) end return contents end # Format drop down box(select) question # def get_selectionbox(question, level) # Note: This question type can not have subquestions contents = "" answers = "\n" question.answers.each do |answer| # Get the user input if available user_answer = nil if (@responses and !@responses.empty?() and @responses.has_key?("#{question.code}") and @responses["#{question.code}"].include?("#{answer.code}")) user_answer = answer.code end # Format answers answers += '<option ' + # If user responses then set on if answer available (((user_answer and !user_answer.blank?() and user_answer.to_s() == answer.code.to_s()) or # If this is a new record and no response have been entered, i.e. this is the # first time the new record form is displayed set on if default ((!@responses or @responses.empty?() or !@responses.has_key?("#{question.code}")) and params['action'] == 'show' and answer.default.upcase == 'Y')) ? ' selected="selected"' : '') answers += ' value="' + answer.code.to_s() + '">' + answer.answer + "</option>\n" end # Note the additional [] in the select_tag name, without this we only get # one choice in params, adding the [] gets all choices as an array html = "\n" + select_tag("responses[#{question.code}][]", raw(answers), :multiple => # Check if multiple choice (question.selectionbox_multiplechoice and !question.selectionbox_multiplechoice.blank?() and question.selectionbox_multiplechoice.upcase == 'Y')) contents += content_tag(:div, content_tag(:p, raw(html)), :class => "select") return contents end # Some questions/sub questions may not actually have any question text, # e.g. sub question. When an error occurs we want to display the text # of the question where the problem has occurred so this function will # try and find the question this object belongs to and display the question # text in the error message # def find_question_text(item_id) text = "" # Retrieve the object with the supplied ident smerf_object = smerf_get_object(item_id, @smerfform.form) # Check if we have reached the root level, if so return # an empty string return text if (smerf_object.parent_id == @smerfform.code) # Retrieve the owner object and see if it is a question, if not # we move up the object tree until a question is found with # question text or we reach the root level smerf_owner_object = smerf_get_owner_object(smerf_object, @smerfform.form) if (!smerf_owner_object.is_a?(SmerfQuestion) or smerf_owner_object.question.blank?()) # Not a question, or no text for this question, recursivly call this function # moving up the tree until we reach the root level or a question with text # is found text = find_question_text(smerf_owner_object.item_id) else text = smerf_owner_object.question end return text.strip() end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/controllers/smerf_test_controller.rb
app/controllers/smerf_test_controller.rb
class SmerfTestController < ApplicationController include Smerf def index # Set the record ID for the user accessing the smerf # normally this would be done by the authentication code # for the application, the test app does not use authentication # so we set it here as an example self.smerf_user_id = 1 end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/models/smerf_answer.rb
app/models/smerf_answer.rb
# This class contains details about answers to form questions, it derives from # SmerfItem. # # It knows how to handle subquestions. Subquestions are additional questions # that a user can answer if certain answers are selected. An example subquestion # would be where an <em>Other</em> is provided as one of the answers to a question, # a subquestion can be defined to display a text field to accept more information. # # Question answers are defined using the following fields: # # code:: Code to uniquely identify the answer, code needs to be unique for each # question (mandatory). The value specified here will be saved as the # users response when the answer is selected. # answer:: The text that will be displayed to the user (mandatory) # default:: If set to Y then this answer will be selected by default (optional) # sort_order:: The sort order for this answer (mandatory) # subquestions:: Some answers may need additional information, another question # can be defined to obtain this information. To define a subquestion # the same fields that define a normal question is used (optional) # # Here is an example answer definition: # # answers: # 1_20: # code: 1 # answer: | 1-20 # sort_order: 1 # default: N # ... # class SmerfAnswer < SmerfItem attr_accessor :code, :answer, :default, :sort_order # A answer object maintains any number of sub-questions, here we alias the # variable that stores the child objects to make code more readable alias :subquestions :child_items def initialize(parent_id, sort_order_field) super(parent_id, sort_order_field) @fields = { 'code' => {'mandatory' => 'Y', 'field_method' => 'code_to_s'}, 'answer' => {'mandatory' => 'Y'}, 'default' => {'mandatory' => 'Y'}, 'sort_order' => {'mandatory' => 'Y'}, 'subquestions' => {'mandatory' => 'N', 'child_items' => 'SmerfQuestion', 'sort_by' => 'sort_order'} } end protected end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/models/smerf_meta_form.rb
app/models/smerf_meta_form.rb
# This class contains details about the form, it derives from SmerfItem. # # When setting up a new form the first thing we do is define some settings for # the form as a whole. Currently the following items can be defined for the form: # # name:: Name of the form (mandatory) # welcome:: Message displayed at the start of the form (optional) # thank_you:: Message displayed at the end of the form (optional) # group_sort_order_field:: Nominates which group field to use when sorting groups # for display (mandatory) # groups:: Defines the question groups within the form (mandatory) # # Here is the definition for the test form included with the plugin: # # --- # smerfform: # name: Test SMERF Form # welcome: | # <b>Welcome:</b><br> # Thank you for taking part in our Test survey we appreciate your # input.<br><br> # # <b>PRIVACY STATEMENT</b><br> # We will keep all the information you provide private and not share # it with anyone else....<br> # # thank_you: | # <b>Thank you for your input.</b><br><br> # # Should you wish to discuss this survey please contact<br> # Joe Bloggs<br> # Tel. 12 345 678<br> # e-mail <A HREF=\"mailto:jbloggs@xyz.com.au\">Joe's email</A><br><br> # # February 2007 # group_sort_order_field: code # # groups: # ... # class SmerfMetaForm < SmerfItem attr_accessor :code, :name, :welcome, :thank_you, :code # Hash that stores the item id and a reference to the object, this # allows us to easily find objects using the item id attr_accessor :item_index # The form object maintains question groups, here we alias the # variable that stores the child objects to make code more readable alias :groups :child_items # Error hash attr_accessor :errors # Most items within a form are uniquely identified by the value assigned # to the code field. Some items need to have unique codes for the complete # form, other need to be unique within a particular parent (e.g. answers # for a particular question). We store codes that are to be unique for # a form in this hash so we can easily check it once all form data has # been processed attr_accessor :class_item_codes def initialize(code) super('','') @code = code @errors = Hash.new() @class_item_codes = Hash.new() @item_index = Hash.new() # Define form fields @fields = { 'name' => {'mandatory' => 'Y'}, 'welcome' => {'mandatory' => 'N'}, 'thank_you' => {'mandatory' => 'N'}, 'groups' => {'mandatory' => 'Y', 'child_items' => 'SmerfGroup'}, 'group_sort_order_field' => {'mandatory' => 'Y', 'sort_field' => 'Y'} } end # Method to process data def process(data, form_object) super(data, form_object) # Remove variables we do not need to save to DB remove_instance_variable(:@class_item_codes) end # Method adds error message to error array def error(attribute, msg) @errors[attribute.to_s] = [] if @errors[attribute.to_s].nil? @errors[attribute.to_s] << msg end # This method will add the specified code to the hash, it will return # false if the code already exists for the specified class def class_item_code(classname, code, parent='') @class_item_codes[classname.to_s] = Hash.new() if (!@class_item_codes.has_key?(classname.to_s)) if (parent.blank?) return false if (@class_item_codes[classname.to_s].has_key?(code.to_s)) @class_item_codes[classname.to_s][code.to_s] = '1' else @class_item_codes[classname.to_s][parent.to_s] = Hash.new() if (!@class_item_codes[classname.to_s].has_key?(parent.to_s)) return false if (@class_item_codes[classname.to_s][parent.to_s].has_key?(code.to_s)) @class_item_codes[classname.to_s][parent.to_s][code.to_s] = '1' end return true end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/models/smerf_question.rb
app/models/smerf_question.rb
# This class contains details about form questions, it derives from # SmerfItem. # # A group can contain any number of questions, there must be at least one question # per group. When defining a question you must specify the question type, # the type determines the type of form field that will be created. # There are currently four types that can be used, this will be expanded as # needed. The current question types are: # # multiplechoice:: Allows the user to select all of the answers that apply from a # list of possible choices, check boxes are used for this question # type as multiple selections can be made # singlechoice:: Allows the user to select one answer from a list of possible choices, # radio buttons are used for the question type as only a single answer # can be selected # textbox:: Allows the user to enter a large amount of free text, the size of the # text box can be specified # textfield:: Allows the user to enter a small amount of free form text, the size # of the text field can be specified # selectionbox:: Allows the user to select one or more answers from a dropdown list # of possible choices # # The following fields can be used to define a question: # # code:: Unique code that will identify the question, the code must be unique within # a form (mandatory) # type:: Specifies the type of field that should be constructed on the form for # this question, see above list for current types (mandatory) # question:: The text of the question, this field is optional as subquestions do # not have to have question text # textbox_size:: Specifies the size of the text box to construct, rows x cols, # defaults to 30x5 (optional) # textfield_size:: Specified the size of the text field that should be constructed, # specified in the number of visible characters, default to 30 (optional) # header:: Specifies a separate heading for the question. The text will be # displayed above the question allowing questions to be broken up into # subsections (optional) # sort_order:: Specifies the sort order for the question # help:: Help text that will be displayed below the question # answers:: Defines the answers to the question if the question type displays a # list of possibilities to the user # validation:: Specifies the validation methods (comma separated) that should be # executed for this question, see Validation and Errors section for # more details # selectionbox_multiplechoice:: Specifies if the dropdown box should allow multiple choices # # Below is an example question definition: # # questions: # specify_your_age: # code: g1q1 # type: singlechoice # sort_order: 1 # question: | Specify your ages # help: | Select the <b>one</b> that apply # validation: validate_mandatory_question # ... # class SmerfQuestion < SmerfItem attr_accessor :code, :type, :question, :sort_order, :help, :textbox_size attr_accessor :textfield_size, :header, :validation, :selectionbox_multiplechoice # A question object maintains any number of answers, here we alias the # variable that stores the child objects to make code more readable alias :answers :child_items def initialize(parent_id, sort_order_field) super(parent_id, sort_order_field) @fields = { 'code' => {'mandatory' => 'Y', 'field_method' => 'code_to_s'}, 'type' => {'mandatory' => 'Y', 'field_method' => 'check_question_type'}, 'question' => {'mandatory' => 'N'}, 'sort_order' => {'mandatory' => 'Y'}, 'help' => {'mandatory' => 'N'}, 'answers' => {'mandatory' => 'N', 'child_items' => 'SmerfAnswer', 'sort_by' => 'sort_order', 'unique_code_check' => 'parent'}, 'textbox_size' => {'mandatory' => 'N'}, 'textfield_size' => {'mandatory' => 'N'}, 'header' => {'mandatory' => 'N'}, 'selectionbox_multiplechoice' => {'mandatory' => 'N'}, 'validation' => {'mandatory' => 'N'}, } end protected # Additional validation method to make sure a valid question type # has been used # def check_question_type case @type when 'multiplechoice' when 'textbox' when 'singlechoice' when 'textfield' when 'selectionbox' else msg = "Invalid question type #{@type} specified" msg = msg + " for #{@data_id}" if (!@data_id.blank?) @form_object.error(self.class, msg) end end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/models/smerf_item.rb
app/models/smerf_item.rb
# SmerfItem class is a base class used by all other smerf classes # and contains shared functionality. # # Derived classes include: # # * SmerfMetaForm # * SmerfGroup # * SmerfQuestion # * SmerfAnswer # class SmerfItem attr_accessor :child_items, :data_id, :item_id, :parent_id def initialize(parent_id='', sort_order_field='') # Item id of the owner of this item @parent_id = parent_id # Init this items id @item_id = '' # Name of the field used for sorting this item @sort_order_field = sort_order_field # Items may have child items, a form has groups, groups have questions # and so on, this hash stores the field name and the class name for these # child items, e.g. field name = groups, class name = SmerfGroup @child_item_fields ||= Hash.new() # This hash stores the field to be used to sort child items, the field # must be one of the ones used to define the child item. For example, # if we want to sort groups by the group name we would set the # group_sort_order_field to name @child_item_sort_order_fields ||= Hash.new() # Most items within a form are uniquely identified by the value assigned # to the code field. Some items need to have unique codes for the complete # form, other need to be unique within a particular parent (e.g. answers # for a particular question). @unique_code_check ||= 'form' # Hash that contains all the fields used to define each item. The items in # this array is defined in the derived class for example SmerfGroup @fields ||= Hash.new() # Array holds all child item objects for this item, e.g. for a group # item it will contain all the questions that belong to the group @child_items ||= Array.new() # Variable that hold the SmerfMetaForm object @form_object ||= nil # Variables used to store the decoded data passed to this item # for processing @data ||= nil @data_id ||= '' end # Method to process data def process(data, form_object) @form_object = form_object if (!data.blank?) # Decode the data decode_data(data) # Check and make sure all fields that define this item in the form # definition file is correct check_item_fields() # If this item is to be sorted make sure the field used for # sorting exists check_sort_order_field() # Create a unique id for this object @item_id = get_item_id() # Process child items if required process_child_items() # Remove any variables that we do not want to save to the DB cleanup() # Add the object to the item_index hash @form_object.item_index[@item_id.to_s] = self end end private # Decode the data def decode_data(data) return if (data.blank?) if (data.kind_of?(Hash) and data.has_key?('smerfform') and !data['smerfform'].blank?) @data = data['smerfform'] @data_id = 'smerfform' elsif (data.kind_of?(Array) and data.size == 2) @data = data[1] @data_id = data[0] end if (@data.blank?) msg = "Invalid data found" msg +=" for #{@data_id}" if (!@data_id.blank?) raise(msg) end end # This method receives a hash that contains the data for the item as retrieved # from the form definition file. We use the array that contains the fields # that define this item and make sure they have been specified correctly. def check_item_fields # Process each field for this item @fields.each do |field, options| # If manadatory make sure it exists and a value have been defined rc = true rc = check_mandatory(field) if (options.has_key?('mandatory') and options['mandatory'] == 'Y') # Check if this field contains child items, if so add to hash @child_item_fields[field] = options['child_items'] if (options.has_key?('child_items') and !options['child_items'].blank?) # Some child items are sorted by a field specified in the form definition # file (e.g. groups), others such as questions are sorted by a fixed # sort order field (i.e. sort_order) if (rc == true and options.has_key?('sort_field') and options['sort_field'] == 'Y') @child_item_sort_order_fields = @data[field] elsif (@child_item_sort_order_fields.kind_of?(Hash) and options.has_key?('sort_by') and !options['sort_by'].blank?) @child_item_sort_order_fields[field] = options['sort_by'] end # Get the method to use when checking for duplicate codes @unique_code_check = options['unique_code_check'] if (options.has_key?('unique_code_check') and !options['unique_code_check'].blank?) # Create an instance variable for the field and set to nil instance_variable_set("@#{field}", nil) # If the field exists then we set the instance variable for that field. # For example we define 'code' as a field, here we extract the value for # code and assign it to @code which is the instance variable for code. if (rc == true and !@data.blank?() and @data.has_key?(field) and !@data[field].blank?) instance_variable_set("@#{field}", @data[field]) logger.info "*** @#{field}:: #{@data[field]}" # Check if a method has been defined for this field, if so call it now if (options.has_key?('field_method') and !options['field_method'].blank? and self.respond_to?(options['field_method'])) # Call the function self.send(options['field_method']) end end end end # The method checks the form definition file data to see if the specified # field exists, it also checks to see if a value has been specified for the # field. def check_mandatory(field) if (@data.blank?() or !@data.has_key?(field) or @data[field].blank?) msg = "No '#{field}' specified" msg += " for #{@data_id}" if (!@data_id.blank?) @form_object.error(self.class, msg) return false end return true end # If this item is to be sorted make sure that the field that will be used # for sorting actually exists, e.g. if groups are to be sorted by name # we want to make sure that the name field exists and has a value def check_sort_order_field if (!@sort_order_field.blank? and (@data.blank?() or !@data.has_key?(@sort_order_field) or @data[@sort_order_field].blank?)) msg = "Specified sort order field '#{@sort_order_field}' could not be found" msg += " for #{@data_id}" if (!@data_id.blank?) @form_object.error(self.class, msg) end end # This method will create and process any child items that belong to this # item. for example if we are processing a group then the group will contain # a number of questions. def process_child_items @child_item_fields.each do |field, classname| process_child_item(field, classname) # Check to make sure all child item sort fields are present and correct # if any problems found do not sort. If for example the definition file # has a question that do not have the sort_order field defined then # an obscure error will be generated as the sort will fail. rc = false @child_items.each do |item| rc = (item.respond_to?(sort_field(field)) and item.send(sort_field(field)).blank?) if (rc == false) end # Sort the child items if required @child_items = @child_items.sort { |a, b| eval("a.#{sort_field(field)}<=>b.#{sort_field(field)}") } if (rc == false and @child_items.size > 0 and !sort_field(field).blank?) end end # Create a new object for the child item using the class name given to us, # then process the new child item. def process_child_item(field, classname) return if (!@data.has_key?(field) or @data[field].blank?) @data[field].each do |child_item_data| # Create a new child object using the class name passed to us child_item = Object.const_get(classname).new(@item_id, sort_field(field)) # Process the new child item child_item.process(child_item_data, @form_object) # We store all child objects in an array, add new object to array @child_items << child_item # Check for duplicate codes check_duplicate_codes(child_item) end end # This method creates a unique id for this item, which is a combination # of onwer_id and this objects unique code def get_item_id code = self.send('code') if (self.respond_to?('code')) @item_id = (@parent_id and !code.blank?) ? "#{@parent_id}~~#{code}" : "#{@form_object.code}" end # This method checks for duplicate code values. We uniquely ID each item # (group, question, ...) using a code. def check_duplicate_codes(object) # Get the code for the item given to us child_item_code = '' child_item_code = object.send('code') if (object.respond_to?('code')) return if (child_item_code.blank?) # Get the code for this item which is the parent code = '' code = self.send('code') if (self.respond_to?('code') and @unique_code_check == 'parent') # Check if the code already exists, if the code check = 'parent' then we make # sure the code is unique within the parent (e.g. answers within questions) # otherwise the check is made form wide, all group codes need to be unique # for a form for example if (!@form_object.class_item_code(object.class.to_s, child_item_code, code)) msg = "Duplicate 'code' found for #{object.class.to_s}" msg += " (#{object.data_id})" if (!object.data_id.blank?) msg += " in #{@data_id}" if (!@data_id.blank?) @form_object.error(self.class, msg) end end # The sort order for items can be specified in the form definition file as # is the case with groups or they are fixed as it the case with questions # where the sort_order field is the field used for sorting. Here we decide # which field to use. def sort_field(field) (@child_item_sort_order_fields.kind_of?(Hash)) ? @child_item_sort_order_fields[field] : @child_item_sort_order_fields end # Cleanup all vars that do not need to be saved to the DB def cleanup remove_instance_variable(:@data) remove_instance_variable(:@data_id) remove_instance_variable(:@sort_order_field) remove_instance_variable(:@child_item_fields) remove_instance_variable(:@child_item_sort_order_fields) remove_instance_variable(:@unique_code_check) remove_instance_variable(:@fields) end protected # Store codes as a string, if we don't then numeric codes # will have problems as we do comparisons with responsed pulled # directly from the http request where all codes are strings. def code_to_s @code = @code.to_s end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/models/smerf_file.rb
app/models/smerf_file.rb
# This class contains functions to work with the smerf form definition file. It # will read the file validating the format of the file, if any errors are # found a <em>RuntimeError</em> exception will be raised. # # Once the file has been validated all objects created during the process # will be serialized to the smerf_forms DB table. Subsequent calls to the form # will simplay unserialize the objects from the DB rather then reporcessing # the definition file. # # If changes are made to the definition file the system will again call functions # within this class to rebuild the form objects. Refer to the rebuild_cache method # within the smerfform.rb file to see how this all works. # class SmerfFile def initialize @smerf_form_object = nil @code = '' end # This method checks if the form definition file has been modified by # comparing the timestamp of the form definition file against the timestamp # stored in the smerf_forms DB table, if they are not the same the form is rebuilt. # def SmerfFile.modified?(code, db_timestamp) smerf_fname = SmerfFile.file_exists?(code) if (ActiveRecord::Base.default_timezone == :utc) (File.mtime(smerf_fname).utc != db_timestamp) else (File.mtime(smerf_fname) != db_timestamp) end end # When a new SmerfFile object is created this method gets executed. It performs # a number of function including: # # * make sure the form definition file actually exists # * opens and reads all the data from the file # * processes the file creating the required form objects # * check for errors # # Refer to the rebuild_cache method within the smerfform.rb file. # def process(code) @code = code # Get the form file name after making sure the file exists smerf_fname = SmerfFile.file_exists?(code) # Load form data from YAML file data = YAML::load(File.open(smerf_fname)) raise("#{smerf_fname} is blank nothing to do") if (data.blank?) # Make sure this is a smerf form file if (data.kind_of?(Hash) and data.size > 0 and data.has_key?('smerfform') and !data['smerfform'].blank?) # Process form data, building form objects as required smerf_form_object = SmerfMetaForm.new(@code) smerf_form_object.process(data, smerf_form_object) # Throw exception if any errors exist check_for_errors(smerf_form_object.errors) else raise("#{smerf_fname} is not a valid smerf form file") end return smerf_form_object end private # This is a small helper method that checks the errors string to see if there # are any errors present, if so we raise an exception # def check_for_errors(errors) # Throw exception if errors found if errors.size > 0 error_msg = "Errors found in form configuration file #{SmerfFile.smerf_file_name(@code)}:\n" errors.each do |attribute, messages| messages.each do |message| error_msg += "#{attribute}: #{message}\n" end end raise(error_msg) end end # Check if the form file exists def SmerfFile.file_exists?(code) filename = SmerfFile.smerf_file_name(code) if (!File.file?(filename)) raise(RuntimeError, "Form configuration file #{filename} not found.") else return filename end end # Functions format file name from supplied form code # Class method def SmerfFile.smerf_file_name(code) "#{RAILS_ROOT}/smerf/#{code}.yml" end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/models/smerf_form.rb
app/models/smerf_form.rb
# Require required for mixin of helper methods require "smerf_system_helpers" require "smerf_helpers" # This model class manages the smerf_forms DB table and stores details about smerf forms. # One of the main function it performs it to rebuild a form from a form # definition file if required. # class SmerfForm < ActiveRecord::Base # Add smerf helper methods to this class include SmerfSystemHelpers include SmerfHelpers has_many :users, :through => :smerf_forms_users validates_presence_of :name, :code, :active validates_length_of :name, :allow_nil => false, :maximum => 50 validates_length_of :code, :allow_nil => false, :maximum => 20 validates_uniqueness_of :code # We read the form contents from a form definition file, we then # save the results in YAML format to this DB field. Doing this prevents # us from having to read and process the definition file everytime the # form needs to be displayed. We check the form definition file date # against a date we store in the DB to determine if we need to rebuild. # # We override the attribute reader for cache so that we only unserialize # it the first time this field is accessed, it also allows us to initialize # class variables which can not be serialized as they store object references # which are initialized at run time (see below) # serialize :cache @unserialized_cache = nil # This method retrieves a form record using the name of the form which # is the same name as the form definition file. If the file is called # <tt>testsmerf.yml</tt> then the <em>code</em> parameter should be # <tt>testsmerf</tt>. # def SmerfForm.find_by_code(code) smerfform = SmerfForm.find(:first, :conditions => "code = '#{code}'") # Create a new smerfform object if record not found smerfform = SmerfForm.new() if (!smerfform) return smerfform end # This method processed a form definition file and stores the results in # the smerf_forms DB record. # # When a form definition file is seen for the first time, it will be processed # and all resultant objects created during the processing of the file will be # serialized to the <em>cache</em> field within the form record. The # <em>cache_date</em> is updated with the current date and time. # # Subsequently the form will be retrieved directly from the DB record rather # than having to rebuilt from the definition file. The timestamp of the file # is checked against the value stored in the <em>cache_date</em> field, if they # are different the form definition will be reprocessed. # def rebuild_cache(code) return if (!self.code.blank?() and !SmerfFile.modified?(code, self.cache_date)) # First clear the current cache self.cache = nil ; self.save if (!code.blank?) self.cache = Hash.new # Build the form and save to cache smerffile = SmerfFile.new smerfmetaform = smerffile.process(code) self.cache[:smerfform] = smerfmetaform self.cache_date = File.mtime(SmerfFile.smerf_file_name(code)).utc if (self.code.blank?()) # Set code self.code = code # Set as active self.active = 1 end # Assign the name as it may have changed self.name = smerfmetaform.name # Save the changes self.save!() end # This method checks if the form is active, returns true if it is. # def active? (self.active == 1) end # Override read attribute accessor for the cache attribute so that we only # unserialize this field once which improves performance, it also allows # us to initialize class variables which are not serialized # def cache # Unserialize the data cache = unserialize_attribute('cache') self[:cache] = cache end # Alias to smerfform.cache[:smerfform] # def form @unserialized_cache = self.cache if (!@unserialized_cache) return @unserialized_cache[:smerfform] end # This method validates all user responses. # # All validations are specified as part of the question (or subquestion) definition # using the 'validation:' field. The SMERF validation system is very flexible and # allows any number of validation methods to be specified for a question by comma # separating each method. # # validation: validate_mandatory_question, validate_years # # Currently there are two validation methods provided with the plugin: # # validate_mandatory_question:: This method will ensure that the user has answered # the question # validate_sub_question:: Only applies to subquestions and makes sure that the user # has selected the answer that relates to the subquestion, it # will also ensure the subquestion has been answered if the # answer that relates to the subquestion has been selected. # # SMERF also allows you to define your own custom validation methods. During # the installation process SMERF creates a helper module called smerf_helpers.rb in # the /lib directory. You can add new validation methods into this module and # access them by simply referencing them in the form definition file. For example # we have question 'How many years have you worked in the industry' and we want # to ensure that the answer provided is between 0-99 we can create a new validation # method called 'validate_years'. # # # Example validation method for "How many years have you worked in the industry" # # it uses a regex to make sure 0-99 years specified. # # def validate_years(question, responses, form) # # Validate entry and make sure years are numeric and between 0-99 # answer = smerf_get_question_answer(question, responses) # if (answer) # # Expression will return nil if regex fail, also check charcters # # after the match to determine if > 2 numbers specified # res = ("#{answer}" =~ /\d{1,2}/) # return "Years must be between 0 and 99" if (!res or $'.length() > 0) # end # # return nil # end # # Note: There are some helper methods that you can use within these methods included # in the smerf_system_helpers.rb module which you can find in the plugins lib # directory. # # Your question definition may then look like this: # # how_many_years: # code: g2q3 # type: textfield # sort_order: 3 # header: # question: | How many years have you worked in the industry # textfield_size: 10 # validation: validate_mandatory_question, validate_years # help: # # When the form is validated your custom validation method will be called. When # an error is detected, a summary of the errors are displayed at the top of the # form, additionally an error message is displayed for each question that has an # error. This makes it very easy for the user to see which question they need # to fix. # def validate_responses(responses, errors) # Perform all validations by calling the validation helper methods # defined in the SmerfHelpers module call_validations(self.form, responses, errors) end private def call_validations(object, responses, errors) object.child_items.each do |item| if (item.respond_to?('validation') and !item.send('validation').blank?) # Multiple validation functions can be specified by using a comma # between each function validation_functions = item.validation.split(",") validation_functions.each do |validation_function| if (self.respond_to?(validation_function.strip())) # Call the method error_msg = self.send(validation_function.strip(), item, responses, self.form) add_error(errors, error_msg, item) if (!error_msg.blank?()) end end end # Recursivly call this method to navigate all items on the form call_validations(item, responses, errors) end end def add_error(errors, msg, item) errors[item.item_id] = Hash.new if (errors[item.item_id].nil?()) errors[item.item_id]["msg"] = Array.new if (errors[item.item_id]["msg"].nil?()) errors[item.item_id]["msg"] << msg errors[item.item_id]["question"] = item.question end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/app/models/smerf_group.rb
app/models/smerf_group.rb
# This class contains details about smerf form groups, it derives from # SmerfItem. # # Each form is divided up into groups of questions, you must have at least one # group per form. Here are the fields that are currently available when # defining a group: # # code:: This code must be unique for all groups within the form as it is used to identify each group (mandatory) # name:: The name of the group, this is displayed as the group heading (mandatory) # description:: Provide more detailed description/instructions for the group (optional) # questions:: Defines all the questions contained within this group (mandatory) # # Here is the definition for the Personal Details group of the test form: # # personal_details: # code: 1 # name: Personal Details Group # description: | This is a brief description of the Personal Details Group # here we ask you some personal details ... # questions: # ... # class SmerfGroup < SmerfItem attr_accessor :code, :name, :description # A group object maintains any number of questions, here we alias the # variable that stores the child objects to make code more readable alias :questions :child_items def initialize(parent_id, sort_order_field) super(parent_id, sort_order_field) # Define group fields @fields = { 'code' => {'mandatory' => 'Y', 'field_method' => 'code_to_s'}, 'name' => {'mandatory' => 'Y'}, 'questions' => {'mandatory' => 'Y', 'child_items' => 'SmerfQuestion', 'sort_by' => 'sort_order'}, 'description' => {'mandatory' => 'N'} } end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/smerf.rb
lib/smerf.rb
%w{ models controllers helpers views}.each do |dir| path = File.join(File.dirname(__FILE__), 'app', dir) model_path = path if path.include?('models') $LOAD_PATH << path ActiveSupport::Dependencies.autoload_paths << path ActiveSupport::Dependencies.autoload_once_paths.delete(path) end # Include smerf classes once Rails have initialised. We need to do this so # that YAML will be able know how to unserialize smerf forms we # serialize to the DB require "smerf_item" require "smerf_file" require "smerf_group" require "smerf_question" require "smerf_answer" require "smerf_meta_form" module Smerf protected # Method retrieves the user id from the session if it exists def smerf_user_id session[:smerf_user_id] || -1 end # Method stores the specified user id in the session def smerf_user_id=(id) session[:smerf_user_id] = id end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/smerf_system_helpers.rb
lib/smerf_system_helpers.rb
# This module contains some standard helper methods used by smerf. # # All validation methods need to take three parameters: # question:: The SmerfQuestion object to be validated # responses:: Hash containing user responses keyed using the question code # form:: Hash that contains all form objects including groups, questions and answers # # The method needs to return an empty string or nil if no errors or # if there is an error then an error message describing the error should be returned. # # Within the form definition file you specify if a validation is required # on a question by specifying which methods within this module # should be called to perform that validation, e.g. # # specify_your_age: # code: g1q1 # type: singlechoice # sort_order: 1 # question: | Specify your ages # help: | Select the <b>one</b> that apply # validation: validation_mandatory # # Multiple validation methods can be specified by comma separating each method name. # module SmerfSystemHelpers # This method checks to make sure that mandatory questions # have been answered by the user # def validate_mandatory_question(question, responses, form) # Check if the responses hash has a key equal to the question code, if # not we know the question has not been answered if (!smerf_question_answered?(question, responses)) return "Question requires an answer" else return nil end end # This method will perform two checks: # 1. Check if the subquestion has been answered, if so then we want to # make sure that the answer this subquestion relates to has been # answered # 2. If the answer that has a subquestion is answered then make sure the # subquestion has been answered # # This validation method is called from a subquestion, so the object # parameter should be a subquestion # def validate_sub_question(question, responses, form) # Retrieve the owner object of this subquestion answer_object = smerf_get_owner_object(question, form) # Make sure owner object is a SmerfAnswer raise(RuntimeError, "Owner object not a SmerfAnswer") if (!answer_object.kind_of?(SmerfAnswer)) # Get the answer code answer_code = answer_object.code # Retrieve the owner object of the answer question_object = smerf_get_owner_object(answer_object, form) # 1. Make sure that if an answer that has a subquestion is answered that # the subquestion has an answer, e.g. # # Select your skills # Banker # Builder # ... # Other # Please specify # We want to make sure that if 'Other' was selected the 'Please specify' # subquestion has an answer # # Check if the answer this subquestion relates to has been answered if (smerf_question_has_answer?(question_object, responses, answer_code)) # Make sure the subquestion has been answered if (!smerf_question_answered?(question, responses)) return "'#{answer_object.answer}' needs additional information" end end # 2. Make sure that the answer that relates to this subsequestion # has the correct response, e.g. # Select your skills # Banker # Builder # ... # Other # Please specify # We want to make sure 'Other' was selected if the 'Please specify' # subquestion has an answer # # Check if this subquestion has an answer if (smerf_question_answered?(question, responses)) # Check if the correct answer selected if (!smerf_question_has_answer?(question_object, responses, answer_code)) # Check if a different answer provided, if so clear subquestion answer # and notify user. This allows a subquestion to be cleared if the user # decided they want to select a non-subquestion answer. if (smerf_question_answered?(question_object, responses) && question.type == 'singlechoice') # Clear subquetion answers responses.delete(question.code) return "Ambiguous answer provided for question '#{question_object.question.strip}', the answers to this question has been cleared" else return "'#{answer_object.answer}' needs to be selected" end end end return nil end # This method will find the object with the specified object ident # def smerf_get_object(item_id, form) if (form.item_index.has_key?(item_id) and form.item_index[item_id]) return form.item_index[item_id] else raise(RuntimeError, "Object with item_id(#{item_id}) not found or nil") end end # This method will find the owner object of the object passed # in as a parameter # def smerf_get_owner_object(object, form) if (form.item_index.has_key?(object.parent_id) and form.item_index[object.parent_id]) return form.item_index[object.parent_id] else raise(RuntimeError, "Owner object not found or nil") end end # This method check the to see if the supplied question has been answered # def smerf_question_answered?(question, responses) return (responses.has_key?(question.code) and !responses[question.code].blank?()) end # This method will check if the question has the answer passed as a parameter. # Some questions allow multiple answers so we need to check if one of the # answers is equal to the supplied answer. # def smerf_question_has_answer?(question, responses, answer) return (responses.has_key?(question.code) and ((responses[question.code].kind_of?(Hash) and responses[question.code].has_key?("#{answer}")) or (!responses[question.code].blank?() and responses[question.code] == "#{answer}"))) end # This method retrieves the answer to the supplied question, if no answer # found it will return nil. This method may return a hash containing all # answers if the question allows multiple choices. # def smerf_get_question_answer(question, responses) if (!smerf_question_answered?(question, responses)) return nil else return responses[question.code] end end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/generators/smerf_generator.rb
lib/generators/smerf_generator.rb
require 'rails/generators/migration' class SmerfGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) include Rails::Generators::Migration class_option :skip_migration, :type => :boolean, :desc => "Don't generate a migration file for the Smerf tables." attr_accessor :plugin_path attr_accessor :user_model_name, :user_table_name, :user_table_fk_name attr_accessor :link_table_name, :link_table_fk_name, :link_table_model_name, :link_table_model_class_name, :link_table_model_file_name def initialize(args = [], options = {}, config = {}) super @user_model_name = file_name.downcase() @user_table_name = file_name.pluralize() @user_table_fk_name = "#{@user_model_name}_id" if (("smerf_forms" <=> @user_table_name) <= 0) @link_table_name = "smerf_forms_#{@user_table_name}" else @link_table_name = "#{@user_table_name}_smerf_forms" end @link_table_fk_name = "#{@link_table_name.singularize()}_id" @link_table_model_name = @link_table_name.singularize() @link_table_model_class_name = @link_table_model_name.classify() @link_table_model_file_name = @link_table_model_name.underscore() @plugin_path = "vendor/plugins/smerf" end def create_migration unless options.skip_migration? migration_template 'migrate/create_smerfs.rb', "db/migrate/create_smerfs.rb" end end def create_routes route "resources :smerf_forms" end def create_smerf_directory_and_test_form directory 'smerf' end def copy_example_stylesheet copy_file 'public/smerf.css', 'public/stylesheets/smerf.css' end def copy_error_and_help_images copy_file 'public/smerf_error.gif', 'public/images/smerf_error.gif' copy_file 'public/smerf_help.gif', 'public/images/smerf_help.gif' end def helpers copy_file 'lib/smerf_helpers.rb', 'lib/smerf_helpers.rb' end # NOTE: in the original Smerf code the smerf_forms_user.rb and smerf_response.rb files get # generated in the Smerf plugin's app/models folder. Not sure why this is done, but we want # to avoid it for the purposes of gemifying the plugin. def copy_models template 'app/models/smerf_forms_user.rb', "app/models/#{@link_table_model_file_name}.rb" template 'app/models/smerf_response.rb', "app/models/smerf_response.rb" end # NOTE: see note above def copy_controllers template 'app/controllers/smerf_forms_controller.rb', "app/controllers/smerf_forms_controller.rb" end # def init # copy_file 'smerf_init.rb', "config/initializers/smerf_init.rb" # end # # Implement the required interface for Rails::Generators::Migration. # taken from http://github.com/rails/rails/blob/master/activerecord/lib/generators/active_record.rb # def self.next_migration_number(dirname) #:nodoc: if ActiveRecord::Base.timestamped_migrations Time.now.utc.strftime("%Y%m%d%H%M%S") else "%.3d" % (current_migration_number(dirname) + 1) end end #Rails::Generators::Migration.next_migration_number #template # def manifest # record do |m| # # # Migrations # m.migration_template("migrate/create_smerfs.rb", # "db/migrate", {:migration_file_name => 'create_smerfs'}) unless options[:skip_migration] # # # Routes # m.route_resources(:smerf_forms) # # # Create smerf directory and copy test form # m.directory('smerf') # m.file('smerf/testsmerf.yml', 'smerf/testsmerf.yml') # # # Copy example stylesheet # m.file('public/smerf.css', 'public/stylesheets/smerf.css') # # # Copy error and help images # m.file('public/smerf_error.gif', 'public/images/smerf_error.gif') # m.file('public/smerf_help.gif', 'public/images/smerf_help.gif') # # # Helpers # m.file 'lib/smerf_helpers.rb', 'lib/smerf_helpers.rb' # # # Copy models # m.template('app/models/smerf_forms_user.rb', "#{plugin_path}/app/models/#{@link_table_model_file_name}.rb") # m.template('app/models/smerf_response.rb', "#{plugin_path}/app/models/smerf_response.rb") # # # Copy controllers # m.template('app/controllers/smerf_forms_controller.rb', "#{plugin_path}/app/controllers/smerf_forms_controller.rb") # # # init.rb # m.file('smerf_init.rb', "#{plugin_path}/init.rb", :collision => :force) # # # Display INSTALL notes # m.readme "INSTALL" # end # end protected # Custom banner def banner "Usage: #{$0} smerf UserModelName" end def add_options!(opt) opt.separator '' opt.separator 'Options:' opt.on("--skip-migration", "Don't generate a migration files") { |v| options[:skip_migration] = v } end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/generators/templates/smerf_init.rb
lib/generators/templates/smerf_init.rb
# Include hook code here model_path = '' # Setup additional application directory paths %w(controllers helpers models views).each do |code_dir| file_path = File.join(directory, 'app', code_dir) $LOAD_PATH << file_path ActiveSupport::Dependencies.load_paths << file_path # Tell Rails where to look for out plugin's controller files config.controller_paths << file_path if file_path.include?('controllers') # By default Rails uses a template_root of RAILS_ROOT/app/views, the plugin # views are in the plugin directory so we need to tell Rails where they can # be found. I also had to do this to allow the application layout to be used, without # this no layout would be used at all. We place the plugin view directory at the end # of the array so that the application view will be checked first. ActionController::Base.append_view_path file_path if file_path.include?('views') model_path = file_path if file_path.include?('models') end # Include smerf classes once Rails have initialised. We need to do this so # that YAML will be able know how to unserialize smerf forms we # serialize to the DB require "#{model_path}/smerf_item" require "#{model_path}/smerf_file" require "#{model_path}/smerf_group" require "#{model_path}/smerf_question" require "#{model_path}/smerf_answer" require "#{model_path}/smerf_meta_form"
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/generators/templates/app/controllers/smerf_forms_controller.rb
lib/generators/templates/app/controllers/smerf_forms_controller.rb
# This controller contains methods that displays the smerf form, allows # the user to answer or edit responses on the form. The controller has # been developed using REST and responds to the following requests: # # * GET /smerf_forms/smerf_form_file_name - displays specified smerf form # * POST /smerf_forms - creates a new record to save responses # * PUT /smerf_form/1 - updates existing record with responses # class SmerfFormsController < ApplicationController include Smerf # GET /smerf_forms/smerf_form_file_name # # <tt>where smerf_form_file_name = the name of the smerf form definition file to load and process</tt> # # This method displays the specified form using the name of the smerf form # definition file to identify which form to display. If this is the first # time the form is being displayed the form definition file will be read, # processed and the results stored in the survay DB table. Subsequently the # form will be retrieved directly from the DB. # # If the form definition file is modified then the form data in the DB will # be rebuilt from the form definition file. Smerf form definition files are # stored in the /smerf directory. # # To create a link to display a form you can use the Standard REST Path # method used for the show action passing the name of the form definition file # as a parameter, for example # # link_to('Complete Test Smerf Form', smerf_url('testsmerf')) # Here is an example link that will display the <em>testsmerf</em> form # def show # Retrieve the smerf form record, rebuild if required, also # retrieve the responses to this form if they exist retrieve_smerf_form(params[:id]) if (@<%= link_table_model_name %>) # Retrieve the responses @responses = @<%= link_table_model_name %>.responses # Render in edit mode if the user has already completed this form render(:action => "edit") else # Render in create mode if the user have not completed this form render(:action => "create") end end # POST /smerf_forms # # This method creates a new smerfs form record for the user that contains the # users responses to the form. Once the record is saved a message to # inform the user is added to <em>flash[:notice]</em> and displayed on # the form. The form is redisplayed allowing the user to edit there responses # to the questions on the form. # def create # Make sure we have some responses if (params.has_key?("responses")) # Validate user responses validate_responses(params) # Save if no errors if (@errors.empty?()) # Create the record <%= link_table_model_class_name %>.create_records( @smerfform.id, self.smerf_user_id, @responses) flash[:notice] = "#{@smerfform.name} saved successfully" # Show the form again, allowing the user to edit responses render(:action => "edit") end else flash[:notice] = "No responses found in #{@smerfform.name}, nothing saved" end end # PUT /smerf/1 # # This method will update an existing smerf form record for the user with # the updated responses to the question on the form. Once the record is saved # a message to inform the user is added to <em>flash[:notice]</em> and # displayed on the form. The form is redisplayed allowing the user to further # edit there responses to the questions. # def update flash[:notice] = "" # Make sure we have some responses if (params.has_key?("responses")) # Validate user responses validate_responses(params) # Update responses if no errors if (@errors.empty?()) <%= link_table_model_class_name %>.update_records( @smerfform.id, self.smerf_user_id, @responses) flash[:notice] = "#{@smerfform.name} updated successfully" end # Show the form again, allowing the user to edit responses render(:action => "edit") else flash[:notice] = "No responses found in #{@smerfform.name}, nothing saved" end end private # This method retrieves the smerf form and user responses if user # has already completed this form in the past. # def retrieve_smerf_form(id) # Retrieve the smerf form record if it exists @smerfform = SmerfForm.find_by_code(id) # Check if smerf form is active if (!@smerfform.code.blank?() and !@smerfform.active?()) raise(RuntimeError, "#{@smerfform.name} is not active.") end # Check if we need to rebuild the form, the form is built # the first time and then whenever the form definition file # is changed if (@smerfform.code.blank?() or SmerfFile.modified?(params[:id], @smerfform.cache_date)) @smerfform.rebuild_cache(params[:id]) end # Find the smerf form record for the current user @<%= link_table_model_name %> = <%= link_table_model_class_name %>.find_user_smerf_form( self.smerf_user_id, @smerfform.id) end # This method will validate the users responses. # def validate_responses(params) @responses = params['responses'] # Retrieve the smerf form record, rails will raise error if not found @smerfform = SmerfForm.find(params[:smerf_form_id]) # Validate user responses @errors = Hash.new() @smerfform.validate_responses(@responses, @errors) end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/generators/templates/app/models/smerf_forms_user.rb
lib/generators/templates/app/models/smerf_forms_user.rb
# This model class manages the smerf_forms_users DB table. It stores a a record # for each form a user completes. # class <%= link_table_model_class_name %> < ActiveRecord::Base has_many :smerf_responses, :dependent => :destroy validates_presence_of :responses validates_presence_of :<%= user_table_fk_name %> validates_presence_of :smerf_form_id belongs_to :<%= user_model_name %> belongs_to :smerf_form # We save the form responses to the DB in yaml format serialize :responses # This method finds the form record for the specified user and form # def <%= link_table_model_class_name %>.find_user_smerf_form(<%= user_table_fk_name %>, smerf_form_id) # Find the form record for the current user <%= link_table_model_name %> = nil if (<%= user_table_fk_name %> > 0) <%= link_table_model_name %> = <%= link_table_model_class_name %>.find(:first, :conditions => ['smerf_form_id = ? AND <%= user_table_fk_name %> = ?', smerf_form_id, <%= user_table_fk_name %>]) else raise(RuntimeError, "For the form responses to be saved for a user, a record ID for the user table needs to be specified. This can be set by using setter function self.smerf_user_id, e.g. self.smerf_user_id = 1") end return <%= link_table_model_name %> end # Create a record for the user for the current form # def <%= link_table_model_class_name %>.create_records(smerf_form_id, <%= user_table_fk_name %>, responses) transaction do # Create the record for the user <%= link_table_model_name %> = <%= link_table_model_class_name %>.create( :<%= user_table_fk_name %> => <%= user_table_fk_name %>, :smerf_form_id => smerf_form_id, :responses => responses) # Create response records for all user responses responses.each do |question_response| # Check if response is a hash, if so process each response # individually, i.e. each response to a question will have it's # own response record if (question_response[1].kind_of?(Hash) or question_response[1].kind_of?(Array)) question_response[1].each do |multichoice_response| # Bug fix 0.0.4 (thanks Alan Masterson) response = multichoice_response.kind_of?(Array) ? multichoice_response[1] : multichoice_response <%= link_table_model_name %>.smerf_responses << SmerfResponse.new( :question_code => question_response[0], :response => response) if (!response.blank?()) end else <%= link_table_model_name %>.smerf_responses << SmerfResponse.new( :question_code => question_response[0], :response => question_response[1]) if (!question_response[1].blank?()) end end end end # Update a record for the user for the current form # def <%= link_table_model_class_name %>.update_records(smerf_form_id, <%= user_table_fk_name %>, responses) transaction do # Retrieve the response record for the current user <%= link_table_model_name %> = <%= link_table_model_class_name %>.find_user_smerf_form( <%= user_table_fk_name %>, smerf_form_id) if (<%= link_table_model_name %>) # Update the record with the new responses <%= link_table_model_name %>.update_attribute(:responses, responses) # Update response records, we use the activerecord replace method # First we find all the existing responses records for this form current_responses = SmerfResponse.find(:all, :conditions => ["<%= link_table_fk_name %> = ?", <%= link_table_model_name %>.id]) # Process responses, if the response has not changed or it's a new # response add it to the array which we will pass to the replace method. # This method will add the new one's, and delete one's that are not in # the array new_responses = Array.new() responses.each do |question_response| # Check if response is a hash, if so process each response # individually, i.e. each response to a question will have it's # own response record if (question_response[1].kind_of?(Hash) or question_response[1].kind_of?(Array)) question_response[1].each do |multichoice_response| if (!multichoice_response[1].blank?()) # Check if this response already exists, if so we add the # SurveyResponse object to the array, otherwise we create a # new response object # if (found = self.response_exist?(current_responses, question_response[0], multichoice_response[1])) new_responses << found else new_responses << (SmerfResponse.new( :<%= link_table_fk_name %> => <%= link_table_model_name %>.id, :question_code => question_response[0], :response => multichoice_response[1])) end end end else if (!question_response[1].blank?()) # Check if this response already exists, if so we add the # SurveyResponse object to the array, otherwise we create a # new response object # if (found = self.response_exist?(current_responses, question_response[0], question_response[1])) new_responses << found else new_responses << (SmerfResponse.new( :<%= link_table_fk_name %> => <%= link_table_model_name %>.id, :question_code => question_response[0], :response => question_response[1])) end end end end # Pass the array that holds existing(unchanged) responses as well # as new responses to the replace method which will generate deletes # and inserts as required <%= link_table_model_name %>.smerf_responses.replace(new_responses) end end end private # This method checks the responses from the form against those currently # stored in the DB for this form and question. If it exists it will return # the SmerfResponse object retrieved from the DB, otherwise it will return nil # def <%= link_table_model_class_name %>.response_exist?(current_responses, question_code, response) response_object = nil begin current_responses.each do |current_response| if (current_response.question_code == question_code and current_response.response == response) response_object = current_response raise end end rescue end return response_object end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/generators/templates/app/models/smerf_response.rb
lib/generators/templates/app/models/smerf_response.rb
# This model class manages the smerf_responses DB table. It stores the users # responses to questions on a smerf form. # # The users responses to questions on a form are stored in the smerf_responses # table which stores a separate record for each response to a question. If a # question has multiple answers then multiple records will be created for the # question. Responses for a question can be found by using the unique question # code assigned within the form definition file. So for example if we had a # question with code 'g1q1' and the user selects two answers which have been # assigned code values 3 and 5 then two records will be created, i.e. # # g1q1, 3 # g1q1, 5 # # This allows analysis of form responses via SQL. class SmerfResponse < ActiveRecord::Base validates_presence_of :<%= link_table_fk_name %> validates_presence_of :question_code validates_presence_of :response belongs_to :<%= link_table_model_name %> end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/generators/templates/lib/smerf_helpers.rb
lib/generators/templates/lib/smerf_helpers.rb
require 'smerf_system_helpers' # This module contains helper methods used by smerf, in particular # custom user defined validation methods that are used to validate user responses. # # All validation methods need to take three parameters: # question:: The SmerfQuestion object to be validated # responses:: Hash containing user responses keyed using the question code # form:: Hash that contains all form objects including groups, questions and answers # # The method needs to return an empty string or nil if no errors or # if there is an error then an error message describing the error should be returned. # # Within the form definition file you specify if a validation is required # on a question by specifying which methods within this module # should be called to perform that validation, e.g. # # specify_your_age: # code: g1q1 # type: singlechoice # sort_order: 1 # question: | Specify your ages # help: | Select the <b>one</b> that apply # validation: validation_mandatory # # Multiple validation methods can be specified by comma separating each method name, # there are also some standard validation methods supplied with smerf that can be used # as well as your own defined within this module. # module SmerfHelpers # Example validation method for "How many years have you worked in the industry" # it uses a regex to make sure 0-99 years specified. # def validate_years(question, responses, form) # Validate entry and make sure years are numeric and between 0-99 answer = smerf_get_question_answer(question, responses) if (answer) # Expression will return nil if regex fail, also check charcters # after the match to determine if > 2 numbers specified res = ("#{answer}" =~ /\d{1,2}/) return "Years must be between 0 and 99" if (!res or $'.length() > 0) end return nil end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
springbok/smerf
https://github.com/springbok/smerf/blob/e75ee66c599918a51257a02e5cd1b5625ebfcb9d/lib/generators/templates/migrate/create_smerfs.rb
lib/generators/templates/migrate/create_smerfs.rb
class CreateSmerfs < ActiveRecord::Migration def self.up # Create table to hold smerf form data create_table :smerf_forms, :primary_key => :id, :force => true do |t| t.string :name, :null => false t.string :code, :null => false t.integer :active, :null => false t.text :cache t.timestamp :cache_date end add_index :smerf_forms, [:code], :unique => true # Create link table between the <%= user_table_name %> and smerf_forms table # which is used to record that the user completed and save the form create_table :<%= link_table_name %>, :primary_key => :id, :force => true do |t| t.integer :<%= user_table_fk_name %>, :null => false t.integer :smerf_form_id, :null => false t.text :responses, :null => false end # Create table to store user responses to each of the questions on the form create_table :smerf_responses, :primary_key => :id, :force => true do |t| t.integer :<%= link_table_fk_name %>, :null => false t.string :question_code, :null => false t.text :response, :null => false end end def self.down drop_table :smerf_responses drop_table :<%= link_table_name %> drop_table :smerf_forms end end
ruby
MIT
e75ee66c599918a51257a02e5cd1b5625ebfcb9d
2026-01-04T17:47:00.942481Z
false
basecamp/platform_agent
https://github.com/basecamp/platform_agent/blob/fc4b05267986bb49ae05b109a7a2a82c74fade73/test/platform_agent_test.rb
test/platform_agent_test.rb
require 'active_support' require 'active_support/testing/autorun' require 'platform_agent' class BasecampAgent < PlatformAgent def ios_app? match? /BC3 iOS/ end def android_app? match? /BC3 Android/ end def mac_app? match?(/Electron/) && match?(/basecamp3/) && match?(/Macintosh/) end def windows_app? match?(/Electron/) && match?(/basecamp3/) && match?(/Windows/) end end class PlatformAgentTest < ActiveSupport::TestCase WINDOWS_PHONE = 'Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 520) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537' CHROME_DESKTOP = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' CHROME_ANDROID = 'Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/_BuildID_) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36' SAFARI_IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4' SAFARI_IPAD = 'Mozilla/5.0 (iPad; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4' BASECAMP_MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) basecamp3/1.0.2 Chrome/47.0.2526.110 Electron/0.36.7 Safari/537.36' BASECAMP_WINDOWS = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) basecamp3/1.0.2 Chrome/49.0.2623.75 Electron/0.36.7 Safari/537.36' BASECAMP_IPAD = 'BC3 iOS/3.0.1 (build 13; iPad Air 2); iOS 9.3' BASECAMP_IPHONE = 'BC3 iOS/3.0.1 (build 13; iPhone 6S); iOS 9.3' BASECAMP_ANDROID = 'BC3 Android/3.0.1 (build 13; Galaxy S3); Marshmallow' test "chrome is via web" do assert_equal "web", platform(CHROME_DESKTOP) end test "safari iOS is via phone" do assert_equal "phone", platform(SAFARI_IPHONE) end test "safari iPad is via tablet" do assert_equal "tablet", platform(SAFARI_IPAD) end test "basecamp iPhone is via iPhone app" do assert_equal "iPhone app", platform(BASECAMP_IPHONE) end test "basecamp iPad is via iPad app" do assert_equal "iPad app", platform(BASECAMP_IPAD) end test "basecamp Android is via Android app" do assert_equal "Android app", platform(BASECAMP_ANDROID) end test "basecamp Mac is via Mac app" do assert_equal "Mac app", platform(BASECAMP_MAC) end test "basecamp Windows is via Windows app" do assert_equal "Windows app", platform(BASECAMP_WINDOWS) end test "blank user agent is via missing" do assert_equal "missing", platform(nil) end test "other phones are via phone" do assert_equal "phone", platform(WINDOWS_PHONE) end test "non-native app android detection" do assert android_phone?(CHROME_ANDROID), "CHROME_ANDROID should be android phone" assert_not android_phone?(SAFARI_IPHONE), "SAFARI_IPHONE should not be android phone" assert_not android_phone?(BASECAMP_ANDROID), "BC3_ANDROID should not be android phone" end private def platform(agent) BasecampAgent.new(agent).to_s end def android_phone?(agent) BasecampAgent.new(agent).android_phone? end end
ruby
MIT
fc4b05267986bb49ae05b109a7a2a82c74fade73
2026-01-04T17:47:02.594581Z
false
basecamp/platform_agent
https://github.com/basecamp/platform_agent/blob/fc4b05267986bb49ae05b109a7a2a82c74fade73/lib/platform_agent.rb
lib/platform_agent.rb
require "user_agent" class PlatformAgent def initialize(user_agent_string) self.user_agent_string = user_agent_string end delegate :browser, :version, :product, :os, to: :user_agent def desktop? !mobile? end def mobile? phone? || tablet? || mobile_app? end def phone? iphone? || android? || other_phones? end def iphone? match? /iPhone/ end def android_phone? !android_app? && android? end def other_phones? match? /(iPod|Windows Phone|BlackBerry|BB10.*Mobile|Mobile.*Firefox)/ end def tablet? ipad? || match?(/(Kindle|Silk)/) end def ipad? match? /iPad/ end def android? match? /Android/ end def native_app? mobile_app? || desktop_app? end def mobile_app? ios_app? || android_app? end def iphone_app? iphone? && ios_app? end def ipad_app? ipad? && ios_app? end # Must overwrite with app-specific match def ios_app? false end # Must overwrite with app-specific match def android_app? false end def desktop_app? mac_app? || windows_app? end # Must overwrite with app-specific match def mac_app? false end # Must overwrite with app-specific match def windows_app? false end def missing? user_agent_string.nil? end def app_version # App user-agent string is parsed into two separate UserAgent instances, it's the last one that contains the right version user_agent.last.version if native_app? end def to_s case when ipad_app? then "iPad app" when iphone_app? then "iPhone app" when android_app? then "Android app" when mac_app? then "Mac app" when windows_app? then "Windows app" when tablet? then "tablet" when phone? then "phone" when missing? then "missing" else "web" end end private attr_accessor :user_agent_string def match?(pattern) user_agent_string.to_s.match?(pattern) end def user_agent @user_agent ||= UserAgent.parse(user_agent_string) end end
ruby
MIT
fc4b05267986bb49ae05b109a7a2a82c74fade73
2026-01-04T17:47:02.594581Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/spec_helper.rb
spec/spec_helper.rb
require 'simplecov' require 'webmock' require 'vcr' require 'pry' if RUBY_VERSION > "1.8.7" class InceptionFormatter def format(result) Coveralls::SimpleCov::Formatter.new.format(result) end end def setup_formatter SimpleCov.formatter = if ENV['TRAVIS'] || ENV['COVERALLS_REPO_TOKEN'] InceptionFormatter else SimpleCov::Formatter::HTMLFormatter end # SimpleCov.start 'test_frameworks' SimpleCov.start do add_filter do |source_file| source_file.filename =~ /spec/ && !(source_file.filename =~ /fixture/) end end end setup_formatter require 'coveralls' VCR.configure do |c| c.cassette_library_dir = 'fixtures/vcr_cassettes' c.hook_into :webmock end RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus config.include WebMock::API config.expect_with :rspec do |c| c.syntax = [:should, :expect] end config.mock_with :rspec do |c| c.syntax = [:should, :expect] end config.after(:suite) do WebMock.disable! end end def stub_api_post body = "{\"message\":\"\",\"url\":\"\"}" stub_request(:post, Coveralls::API::API_BASE+"/jobs").with( :headers => { 'Accept'=>'*/*; q=0.5, application/xml', 'Accept-Encoding'=>'gzip, deflate', 'Content-Length'=>/.+/, 'Content-Type'=>/.+/, 'User-Agent'=>'Ruby' } ).to_return(:status => 200, :body => body, :headers => {}) end def silence return yield if ENV['silence'] == 'false' silence_stream(STDOUT) do yield end end module Kernel def silence_stream(stream) old_stream = stream.dup stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null') stream.sync = true yield ensure stream.reopen(old_stream) end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/output_spec.rb
spec/coveralls/output_spec.rb
require 'spec_helper' describe Coveralls::Output do it "defaults the IO to $stdout" do old_stdout = $stdout out = StringIO.new $stdout = out Coveralls::Output.puts "this is a test" expect(out.string).to eq "this is a test\n" $stdout = old_stdout end it "accepts an IO injection" do out = StringIO.new Coveralls::Output.output = out Coveralls::Output.puts "this is a test" expect(out.string).to eq "this is a test\n" end describe ".puts" do it "accepts an IO injection" do out = StringIO.new Coveralls::Output.puts "this is a test", :output => out expect(out.string).to eq "this is a test\n" end end describe ".print" do it "accepts an IO injection" do out = StringIO.new Coveralls::Output.print "this is a test", :output => out expect(out.string).to eq "this is a test" end end describe 'when silenced' do before do @original_stdout = $stdout @output = StringIO.new Coveralls::Output.silent = true $stdout = @output end it "should not puts" do Coveralls::Output.puts "foo" @output.rewind @output.read.should == "" end it "should not print" do Coveralls::Output.print "foo" @output.rewind @output.read.should == "" end after do $stdout = @original_stdout end end describe '.format' do it "accepts a color argument" do require 'term/ansicolor' string = 'Hello' ansi_color_string = Term::ANSIColor.red(string) Coveralls::Output.format(string, :color => 'red').should eq(ansi_color_string) end it "also accepts no color arguments" do unformatted_string = "Hi Doggie!" Coveralls::Output.format(unformatted_string).should eq(unformatted_string) end it "rejects formats unrecognized by Term::ANSIColor" do string = 'Hi dog!' Coveralls::Output.format(string, :color => "not_a_real_color").should eq(string) end it "accepts more than 1 color argument" do string = 'Hi dog!' multi_formatted_string = Term::ANSIColor.red{ Term::ANSIColor.underline(string) } Coveralls::Output.format(string, :color => 'red underline').should eq(multi_formatted_string) end context "no color" do before { Coveralls::Output.no_color = true } it "does not add color to string" do unformatted_string = "Hi Doggie!" Coveralls::Output.format(unformatted_string, :color => 'red'). should eq(unformatted_string) end end end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/configuration_spec.rb
spec/coveralls/configuration_spec.rb
require 'spec_helper' describe Coveralls::Configuration do before do ENV.stub(:[]).and_return(nil) end describe '.configuration' do it "returns a hash with the default keys" do config = Coveralls::Configuration.configuration config.should be_a(Hash) config.keys.should include(:environment) config.keys.should include(:git) end context 'yaml_config' do let(:repo_token) { SecureRandom.hex(4) } let(:repo_secret_token) { SecureRandom.hex(4) } let(:yaml_config) { { 'repo_token' => repo_token, 'repo_secret_token' => repo_secret_token } } before do Coveralls::Configuration.stub(:yaml_config).and_return(yaml_config) end it 'sets the Yaml config and associated variables if present' do config = Coveralls::Configuration.configuration config[:configuration].should eq(yaml_config) config[:repo_token].should eq(repo_token) end it 'uses the repo_secret_token if the repo_token is not set' do yaml_config.delete('repo_token') config = Coveralls::Configuration.configuration config[:configuration].should eq(yaml_config) config[:repo_token].should eq(repo_secret_token) end end context 'repo_token in environment' do let(:repo_token) { SecureRandom.hex(4) } before do ENV.stub(:[]).with('COVERALLS_REPO_TOKEN').and_return(repo_token) end it 'pulls the repo token from the environment if set' do config = Coveralls::Configuration.configuration config[:repo_token].should eq(repo_token) end end context 'flag_name in environment' do let(:flag_name) { 'Test Flag' } before do ENV.stub(:[]).with('COVERALLS_FLAG_NAME').and_return(flag_name) end it 'pulls the flag name from the environment if set' do config = Coveralls::Configuration.configuration config[:flag_name].should eq(flag_name) end end context 'Services' do context 'with env based service name' do let(:service_name) { 'travis-enterprise' } before do ENV.stub(:[]).with('TRAVIS').and_return('1') ENV.stub(:[]).with('COVERALLS_SERVICE_NAME').and_return(service_name) end it 'pulls the service name from the environment if set' do config = Coveralls::Configuration.configuration config[:service_name].should eq(service_name) end end context 'on Travis' do before do ENV.stub(:[]).with('TRAVIS').and_return('1') end it 'should set service parameters for this service and no other' do Coveralls::Configuration.should_receive(:set_service_params_for_travis).with(anything, anything) Coveralls::Configuration.should_not_receive(:set_service_params_for_circleci) Coveralls::Configuration.should_not_receive(:set_service_params_for_semaphore) Coveralls::Configuration.should_not_receive(:set_service_params_for_jenkins) Coveralls::Configuration.should_not_receive(:set_service_params_for_coveralls_local) Coveralls::Configuration.should_receive(:set_standard_service_params_for_generic_ci) Coveralls::Configuration.configuration end end context 'on CircleCI' do before do ENV.stub(:[]).with('CIRCLECI').and_return('1') end it 'should set service parameters for this service and no other' do Coveralls::Configuration.should_not_receive(:set_service_params_for_travis) Coveralls::Configuration.should_receive(:set_service_params_for_circleci) Coveralls::Configuration.should_not_receive(:set_service_params_for_semaphore) Coveralls::Configuration.should_not_receive(:set_service_params_for_jenkins) Coveralls::Configuration.should_not_receive(:set_service_params_for_coveralls_local) Coveralls::Configuration.should_receive(:set_standard_service_params_for_generic_ci) Coveralls::Configuration.configuration end end context 'on Semaphore' do before do ENV.stub(:[]).with('SEMAPHORE').and_return('1') end it 'should set service parameters for this service and no other' do Coveralls::Configuration.should_not_receive(:set_service_params_for_travis) Coveralls::Configuration.should_not_receive(:set_service_params_for_circleci) Coveralls::Configuration.should_receive(:set_service_params_for_semaphore) Coveralls::Configuration.should_not_receive(:set_service_params_for_jenkins) Coveralls::Configuration.should_not_receive(:set_service_params_for_coveralls_local) Coveralls::Configuration.should_receive(:set_standard_service_params_for_generic_ci) Coveralls::Configuration.configuration end end context 'when using Jenkins' do before do ENV.stub(:[]).with('JENKINS_URL').and_return('1') end it 'should set service parameters for this service and no other' do Coveralls::Configuration.should_not_receive(:set_service_params_for_travis) Coveralls::Configuration.should_not_receive(:set_service_params_for_circleci) Coveralls::Configuration.should_not_receive(:set_service_params_for_semaphore) Coveralls::Configuration.should_receive(:set_service_params_for_jenkins) Coveralls::Configuration.should_not_receive(:set_service_params_for_coveralls_local) Coveralls::Configuration.should_receive(:set_standard_service_params_for_generic_ci) Coveralls::Configuration.configuration end end context 'when running Coveralls locally' do before do ENV.stub(:[]).with('COVERALLS_RUN_LOCALLY').and_return('1') end it 'should set service parameters for this service and no other' do Coveralls::Configuration.should_not_receive(:set_service_params_for_travis) Coveralls::Configuration.should_not_receive(:set_service_params_for_circleci) Coveralls::Configuration.should_not_receive(:set_service_params_for_semaphore) Coveralls::Configuration.should_not_receive(:set_service_params_for_jenkins) Coveralls::Configuration.should_receive(:set_service_params_for_coveralls_local) Coveralls::Configuration.should_receive(:set_standard_service_params_for_generic_ci) Coveralls::Configuration.configuration end end context 'for generic CI' do before do ENV.stub(:[]).with('CI_NAME').and_return('1') end it 'should set service parameters for this service and no other' do Coveralls::Configuration.should_not_receive(:set_service_params_for_travis) Coveralls::Configuration.should_not_receive(:set_service_params_for_circleci) Coveralls::Configuration.should_not_receive(:set_service_params_for_semaphore) Coveralls::Configuration.should_not_receive(:set_service_params_for_jenkins) Coveralls::Configuration.should_not_receive(:set_service_params_for_coveralls_local) Coveralls::Configuration.should_receive(:set_standard_service_params_for_generic_ci).with(anything) Coveralls::Configuration.configuration end end end end describe '.set_service_params_for_travis' do let(:travis_job_id) { SecureRandom.hex(4) } before do ENV.stub(:[]).with('TRAVIS_JOB_ID').and_return(travis_job_id) end it 'should set the service_job_id' do config = {} Coveralls::Configuration.set_service_params_for_travis(config, nil) config[:service_job_id].should eq(travis_job_id) end it 'should set the service_name to travis-ci by default' do config = {} Coveralls::Configuration.set_service_params_for_travis(config, nil) config[:service_name].should eq('travis-ci') end it 'should set the service_name to a value if one is passed in' do config = {} random_name = SecureRandom.hex(4) Coveralls::Configuration.set_service_params_for_travis(config, random_name) config[:service_name].should eq(random_name) end end describe '.set_service_params_for_circleci' do let(:circle_build_num) { SecureRandom.hex(4) } let(:circle_workflow_id) { nil } before do ENV.stub(:[]).with('CIRCLE_BUILD_NUM').and_return(circle_build_num) ENV.stub(:[]).with('CIRCLE_WORKFLOW_ID').and_return(circle_workflow_id) end it 'should set the expected parameters' do config = {} Coveralls::Configuration.set_service_params_for_circleci(config) config[:service_name].should eq('circleci') config[:service_number].should eq(circle_build_num) end context 'when workflow_id is available' do let(:circle_workflow_id) { SecureRandom.hex(4) } it 'should use workflow ID' do config = {} Coveralls::Configuration.set_service_params_for_circleci(config) config[:service_name].should eq('circleci') config[:service_number].should eq(circle_workflow_id) end end end describe '.set_service_params_for_gitlab' do let(:commit_sha) { SecureRandom.hex(32) } let(:service_job_number) { "spec:one" } let(:service_job_id) { 1234 } let(:service_branch) { "feature" } let(:service_pull_request) { "1" } let(:service_number) { 5678 } before do ENV.stub(:[]).with('CI_BUILD_NAME').and_return(service_job_number) ENV.stub(:[]).with('CI_PIPELINE_ID').and_return(service_number) ENV.stub(:[]).with('CI_BUILD_ID').and_return(service_job_id) ENV.stub(:[]).with('CI_BUILD_REF_NAME').and_return(service_branch) ENV.stub(:[]).with('CI_MERGE_REQUEST_IID').and_return(service_pull_request) ENV.stub(:[]).with('CI_BUILD_REF').and_return(commit_sha) end it 'should set the expected parameters' do config = {} Coveralls::Configuration.set_service_params_for_gitlab(config) config[:service_name].should eq('gitlab-ci') config[:service_number].should eq(service_number) config[:service_job_number].should eq(service_job_number) config[:service_job_id].should eq(service_job_id) config[:service_branch].should eq(service_branch) config[:service_pull_request].should eq(service_pull_request) config[:commit_sha].should eq(commit_sha) end end describe '.set_service_params_for_semaphore' do let(:semaphore_build_num) { SecureRandom.hex(4) } before do ENV.stub(:[]).with('SEMAPHORE_BUILD_NUMBER').and_return(semaphore_build_num) end it 'should set the expected parameters' do config = {} Coveralls::Configuration.set_service_params_for_semaphore(config) config[:service_name].should eq('semaphore') config[:service_number].should eq(semaphore_build_num) end end describe '.set_service_params_for_jenkins' do let(:service_pull_request) { '1234' } let(:build_num) { SecureRandom.hex(4) } before do ENV.stub(:[]).with('CI_PULL_REQUEST').and_return(service_pull_request) ENV.stub(:[]).with('BUILD_NUMBER').and_return(build_num) end it 'should set the expected parameters' do config = {} Coveralls::Configuration.set_service_params_for_jenkins(config) Coveralls::Configuration.set_standard_service_params_for_generic_ci(config) config[:service_name].should eq('jenkins') config[:service_number].should eq(build_num) config[:service_pull_request].should eq(service_pull_request) end end describe '.set_service_params_for_coveralls_local' do it 'should set the expected parameters' do config = {} Coveralls::Configuration.set_service_params_for_coveralls_local(config) config[:service_name].should eq('coveralls-ruby') config[:service_job_id].should be_nil config[:service_event_type].should eq('manual') end end describe '.set_service_params_for_generic_ci' do let(:service_name) { SecureRandom.hex(4) } let(:service_number) { SecureRandom.hex(4) } let(:service_build_url) { SecureRandom.hex(4) } let(:service_branch) { SecureRandom.hex(4) } let(:service_pull_request) { '1234' } before do ENV.stub(:[]).with('CI_NAME').and_return(service_name) ENV.stub(:[]).with('CI_BUILD_NUMBER').and_return(service_number) ENV.stub(:[]).with('CI_BUILD_URL').and_return(service_build_url) ENV.stub(:[]).with('CI_BRANCH').and_return(service_branch) ENV.stub(:[]).with('CI_PULL_REQUEST').and_return(service_pull_request) end it 'should set the expected parameters' do config = {} Coveralls::Configuration.set_standard_service_params_for_generic_ci(config) config[:service_name].should eq(service_name) config[:service_number].should eq(service_number) config[:service_build_url].should eq(service_build_url) config[:service_branch].should eq(service_branch) config[:service_pull_request].should eq(service_pull_request) end end describe '.set_service_params_for_appveyor' do let(:service_number) { SecureRandom.hex(4) } let(:service_branch) { SecureRandom.hex(4) } let(:commit_sha) { SecureRandom.hex(4) } let(:repo_name) { SecureRandom.hex(4) } before do ENV.stub(:[]).with('APPVEYOR_BUILD_VERSION').and_return(service_number) ENV.stub(:[]).with('APPVEYOR_REPO_BRANCH').and_return(service_branch) ENV.stub(:[]).with('APPVEYOR_REPO_COMMIT').and_return(commit_sha) ENV.stub(:[]).with('APPVEYOR_REPO_NAME').and_return(repo_name) end it 'should set the expected parameters' do config = {} Coveralls::Configuration.set_service_params_for_appveyor(config) config[:service_name].should eq('appveyor') config[:service_number].should eq(service_number) config[:service_branch].should eq(service_branch) config[:commit_sha].should eq(commit_sha) config[:service_build_url].should eq('https://ci.appveyor.com/project/%s/build/%s' % [repo_name, service_number]) end end describe '.git' do let(:git_id) { SecureRandom.hex(2) } let(:author_name) { SecureRandom.hex(4) } let(:author_email) { SecureRandom.hex(4) } let(:committer_name) { SecureRandom.hex(4) } let(:committer_email) { SecureRandom.hex(4) } let(:message) { SecureRandom.hex(4) } let(:branch) { SecureRandom.hex(4) } before do allow(ENV).to receive(:fetch).with('GIT_ID', anything).and_return(git_id) allow(ENV).to receive(:fetch).with('GIT_AUTHOR_NAME', anything).and_return(author_name) allow(ENV).to receive(:fetch).with('GIT_AUTHOR_EMAIL', anything).and_return(author_email) allow(ENV).to receive(:fetch).with('GIT_COMMITTER_NAME', anything).and_return(committer_name) allow(ENV).to receive(:fetch).with('GIT_COMMITTER_EMAIL', anything).and_return(committer_email) allow(ENV).to receive(:fetch).with('GIT_MESSAGE', anything).and_return(message) allow(ENV).to receive(:fetch).with('GIT_BRANCH', anything).and_return(branch) end it 'uses ENV vars' do config = Coveralls::Configuration.git config[:head][:id].should eq(git_id) config[:head][:author_name].should eq(author_name) config[:head][:author_email].should eq(author_email) config[:head][:committer_name].should eq(committer_name) config[:head][:committer_email].should eq(committer_email) config[:head][:message].should eq(message) config[:branch].should eq(branch) end end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/coveralls_spec.rb
spec/coveralls/coveralls_spec.rb
require 'spec_helper' describe Coveralls do before do SimpleCov.stub(:start) stub_api_post Coveralls.testing = true end describe "#will_run?" do it "checks CI environemnt variables" do Coveralls.will_run?.should be_truthy end context "with CI disabled" do before do @ci = ENV['CI'] ENV['CI'] = nil @coveralls_run_locally = ENV['COVERALLS_RUN_LOCALLY'] ENV['COVERALLS_RUN_LOCALLY'] = nil Coveralls.testing = false end after do ENV['CI'] = @ci ENV['COVERALLS_RUN_LOCALLY'] = @coveralls_run_locally end it "indicates no run" do Coveralls.will_run?.should be_falsy end end end describe "#should_run?" do it "outputs to stdout when running locally" do Coveralls.testing = false Coveralls.run_locally = true silence do Coveralls.should_run? end end end describe "#wear!" do it "receives block" do ::SimpleCov.should_receive(:start) silence do subject.wear! do add_filter 's' end end end it "uses string" do ::SimpleCov.should_receive(:start).with 'test_frameworks' silence do subject.wear! 'test_frameworks' end end it "uses default" do ::SimpleCov.should_receive(:start).with no_args silence do subject.wear! end ::SimpleCov.filters.map(&:filter_argument).should include 'vendor' end end describe "#wear_merged!" do it "sets formatter to NilFormatter" do ::SimpleCov.should_receive(:start).with 'rails' silence do subject.wear_merged! 'rails' do add_filter "/spec/" end end ::SimpleCov.formatter.should be Coveralls::NilFormatter end end describe "#push!" do it "sends existing test results", :if => RUBY_VERSION >= "1.9" do result = false silence do result = subject.push! end result.should be_truthy end end describe "#setup!" do it "sets SimpleCov adapter" do SimpleCovTmp = SimpleCov Object.send :remove_const, :SimpleCov silence { subject.setup! } SimpleCov = SimpleCovTmp end end after(:all) do setup_formatter end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/simplecov_spec.rb
spec/coveralls/simplecov_spec.rb
require 'spec_helper' describe Coveralls::SimpleCov::Formatter do before do stub_api_post end def source_fixture(filename) File.expand_path( File.join( File.dirname( __FILE__ ), 'fixtures', filename ) ) end let(:result) { SimpleCov::Result.new({ source_fixture( 'sample.rb' ) => [nil, 1, 1, 1, nil, 0, 1, 1, nil, nil], source_fixture( 'app/models/user.rb' ) => [nil, 1, 1, 1, 1, 0, 1, 0, nil, nil], source_fixture( 'app/models/robot.rb' ) => [1, 1, 1, 1, nil, nil, 1, 0, nil, nil], source_fixture( 'app/models/house.rb' ) => [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil], source_fixture( 'app/models/airplane.rb' ) => [0, 0, 0, 0, 0], source_fixture( 'app/models/dog.rb' ) => [1, 1, 1, 1, 1], source_fixture( 'app/controllers/sample.rb' ) => [nil, 1, 1, 1, nil, 0, 1, 1, nil, nil] }) } describe "#format" do context "should run" do before do Coveralls.testing = true Coveralls.noisy = false end it "posts json", :if => RUBY_VERSION >= "1.9" do result.files.should_not be_empty silence do Coveralls::SimpleCov::Formatter.new.format(result).should be_truthy end end end context "should not run, noisy" do it "only displays result" do silence do Coveralls::SimpleCov::Formatter.new.display_result(result).should be_truthy end end end context "no files" do let(:result) { SimpleCov::Result.new({}) } it "shows note that no files have been covered" do Coveralls.noisy = true Coveralls.testing = false silence do expect do Coveralls::SimpleCov::Formatter.new.format(result) end.not_to raise_error end end end context "with api error" do it "rescues" do e = SocketError.new silence do Coveralls::SimpleCov::Formatter.new.display_error(e).should be_falsy end end end context "#get_source_files" do let(:source_files) { Coveralls::SimpleCov::Formatter.new.get_source_files(result) } it "nils the skipped lines" do source_file = source_files.first source_file[:coverage].should_not eq result.files.first.coverage source_file[:coverage].should eq [nil, 1, 1, 1, nil, 0, nil, nil, nil, nil, nil] end end end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/fixtures/sample.rb
spec/coveralls/fixtures/sample.rb
# Foo class class Foo def initialize @foo = 'baz' end # :nocov: def bar @foo end # :nocov: end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/fixtures/app/vendor/vendored_gem.rb
spec/coveralls/fixtures/app/vendor/vendored_gem.rb
# this file should not be covered
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/fixtures/app/controllers/sample.rb
spec/coveralls/fixtures/app/controllers/sample.rb
# Foo class class Foo def initialize @foo = 'baz' end # :nocov: def bar @foo end # :nocov: end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/fixtures/app/models/airplane.rb
spec/coveralls/fixtures/app/models/airplane.rb
# Foo class class Foo def initialize @foo = 'baz' end def bar @foo end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/fixtures/app/models/house.rb
spec/coveralls/fixtures/app/models/house.rb
# Foo class class Foo def initialize @foo = 'baz' end def bar @foo end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/fixtures/app/models/dog.rb
spec/coveralls/fixtures/app/models/dog.rb
# Foo class class Foo def initialize @foo = 'baz' end def bar @foo end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/fixtures/app/models/robot.rb
spec/coveralls/fixtures/app/models/robot.rb
# Foo class class Foo def initialize @foo = 'baz' end def bar @foo end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/spec/coveralls/fixtures/app/models/user.rb
spec/coveralls/fixtures/app/models/user.rb
# Foo class class Foo def initialize @foo = 'baz' end def bar @foo end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/lib/coveralls.rb
lib/coveralls.rb
require "coveralls/version" require "coveralls/configuration" require "coveralls/api" require "coveralls/output" require "coveralls/simplecov" module Coveralls extend self class NilFormatter def format(result) end end attr_accessor :testing, :noisy, :run_locally def wear!(simplecov_setting=nil, &block) setup! start! simplecov_setting, &block end def wear_merged!(simplecov_setting=nil, &block) require 'simplecov' @@adapter = :simplecov ::SimpleCov.formatter = NilFormatter start! simplecov_setting, &block end def push! require 'simplecov' result = ::SimpleCov::ResultMerger.merged_result Coveralls::SimpleCov::Formatter.new.format result end def setup! # Try to load up SimpleCov. @@adapter = nil if defined?(::SimpleCov) @@adapter = :simplecov else begin require 'simplecov' @@adapter = :simplecov if defined?(::SimpleCov) rescue end end # Load the appropriate adapter. if @@adapter == :simplecov ::SimpleCov.formatter = Coveralls::SimpleCov::Formatter Coveralls::Output.puts("[Coveralls] Set up the SimpleCov formatter.", :color => "green") else Coveralls::Output.puts("[Coveralls] Couldn't find an appropriate adapter.", :color => "red") end end def start!(simplecov_setting = 'test_frameworks', &block) if @@adapter == :simplecov ::SimpleCov.add_filter 'vendor' if simplecov_setting Coveralls::Output.puts("[Coveralls] Using SimpleCov's '#{simplecov_setting}' settings.", :color => "green") if block_given? ::SimpleCov.start(simplecov_setting) { instance_eval(&block)} else ::SimpleCov.start(simplecov_setting) end elsif block Coveralls::Output.puts("[Coveralls] Using SimpleCov settings defined in block.", :color => "green") ::SimpleCov.start { instance_eval(&block) } else Coveralls::Output.puts("[Coveralls] Using SimpleCov's default settings.", :color => "green") ::SimpleCov.start end end end def should_run? # Fail early if we're not on a CI unless will_run? Coveralls::Output.puts("[Coveralls] Outside the CI environment, not sending data.", :color => "yellow") return false end if ENV["COVERALLS_RUN_LOCALLY"] || (defined?(@run_locally) && @run_locally) Coveralls::Output.puts("[Coveralls] Creating a new job on Coveralls from local coverage results.", :color => "cyan") end true end def will_run? ENV["CI"] || ENV["JENKINS_URL"] || ENV['TDDIUM'] || ENV["COVERALLS_RUN_LOCALLY"] || (defined?(@testing) && @testing) end def noisy? ENV["COVERALLS_NOISY"] || (defined?(@noisy) && @noisy) end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/lib/coveralls/command.rb
lib/coveralls/command.rb
require "thor" module Coveralls class CommandLine < Thor desc "push", "Runs your test suite and pushes the coverage results to Coveralls." def push return unless ensure_can_run_locally! ENV["COVERALLS_RUN_LOCALLY"] = "true" cmds = ["bundle exec rake"] if File.exist?('.travis.yml') cmds = YAML.load_file('.travis.yml')["script"] || cmds rescue cmds end cmds.each { |cmd| system cmd } ENV["COVERALLS_RUN_LOCALLY"] = nil end desc "report", "Runs your test suite locally and displays coverage statistics." def report ENV["COVERALLS_NOISY"] = "true" exec "bundle exec rake" ENV["COVERALLS_NOISY"] = nil end desc "open", "View this repository on Coveralls." def open open_token_based_url "https://coveralls.io/repos/%@" end desc "service", "View this repository on your CI service's website." def service open_token_based_url "https://coveralls.io/repos/%@/service" end desc "last", "View the last build for this repository on Coveralls." def last open_token_based_url "https://coveralls.io/repos/%@/last_build" end desc "version", "See version" def version Coveralls::Output.puts Coveralls::VERSION end private def open_token_based_url url config = Coveralls::Configuration.configuration if config[:repo_token] url = url.gsub("%@", config[:repo_token]) `open #{url}` else Coveralls::Output.puts "No repo_token configured." end end def ensure_can_run_locally! config = Coveralls::Configuration.configuration if config[:repo_token].nil? Coveralls::Output.puts "Coveralls cannot run locally because no repo_secret_token is set in .coveralls.yml", :color => "red" Coveralls::Output.puts "Please try again when you get your act together.", :color => "red" return false end true end end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/lib/coveralls/version.rb
lib/coveralls/version.rb
module Coveralls VERSION = "0.8.23" end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/lib/coveralls/simplecov.rb
lib/coveralls/simplecov.rb
module Coveralls module SimpleCov class Formatter def display_result(result) # Log which files would be submitted. if result.files.length > 0 Coveralls::Output.puts "[Coveralls] Some handy coverage stats:" else Coveralls::Output.puts "[Coveralls] There are no covered files.", :color => "yellow" end result.files.each do |f| Coveralls::Output.print " * " Coveralls::Output.print short_filename(f.filename).to_s, :color => "cyan" Coveralls::Output.print " => ", :color => "white" cov = "#{f.covered_percent.round}%" if f.covered_percent > 90 Coveralls::Output.print cov, :color => "green" elsif f.covered_percent > 80 Coveralls::Output.print cov, :color => "yellow" else Coveralls::Output.print cov, :color => "red" end Coveralls::Output.puts "" end true end def get_source_files(result) # Gather the source files. source_files = [] result.files.each do |file| properties = {} # Get Source properties[:source] = File.open(file.filename, "rb:utf-8").read # Get the root-relative filename properties[:name] = short_filename(file.filename) # Get the coverage properties[:coverage] = file.coverage.dup # Skip nocov lines file.lines.each_with_index do |line, i| properties[:coverage][i] = nil if line.skipped? end source_files << properties end source_files end def format(result) unless Coveralls.should_run? if Coveralls.noisy? display_result result end return end # Post to Coveralls. API.post_json "jobs", :source_files => get_source_files(result), :test_framework => result.command_name.downcase, :run_at => result.created_at Coveralls::Output.puts output_message result true rescue Exception => e display_error e end def display_error(e) Coveralls::Output.puts "Coveralls encountered an exception:", :color => "red" Coveralls::Output.puts e.class.to_s, :color => "red" Coveralls::Output.puts e.message, :color => "red" e.backtrace.each do |line| Coveralls::Output.puts line, :color => "red" end if e.backtrace if e.respond_to?(:response) && e.response Coveralls::Output.puts e.response.to_s, :color => "red" end false end def output_message(result) "Coverage is at #{result.covered_percent.round(2) rescue result.covered_percent.round}%.\nCoverage report sent to Coveralls." end def short_filename(filename) filename = filename.gsub(::SimpleCov.root, '.').gsub(/^\.\//, '') if ::SimpleCov.root filename end end end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/lib/coveralls/output.rb
lib/coveralls/output.rb
module Coveralls # # Public: Methods for formatting strings with Term::ANSIColor. # Does not utilize monkey-patching and should play nicely when # included with other libraries. # # All methods are module methods and should be called on # the Coveralls::Output module. # # Examples # # Coveralls::Output.format("Hello World", :color => "cyan") # # => "\e[36mHello World\e[0m" # # Coveralls::Output.print("Hello World") # # Hello World => nil # # Coveralls::Output.puts("Hello World", :color => "underline") # # Hello World # # => nil # # To silence output completely: # # Coveralls::Output.silent = true # # or set this environment variable: # # COVERALLS_SILENT # # To disable color completely: # # Coveralls::Output.no_color = true module Output attr_accessor :silent, :no_color attr_writer :output extend self def output (defined?(@output) && @output) || $stdout end def no_color? (defined?(@no_color)) && @no_color end # Public: Formats the given string with the specified color # through Term::ANSIColor # # string - the text to be formatted # options - The hash of options used for formatting the text: # :color - The color to be passed as a method to # Term::ANSIColor # # Examples # # Coveralls::Output.format("Hello World!", :color => "cyan") # # => "\e[36mHello World\e[0m" # # Returns the formatted string. def format(string, options = {}) unless no_color? require 'term/ansicolor' if options[:color] options[:color].split(/\s/).reverse_each do |color| if Term::ANSIColor.respond_to?(color.to_sym) string = Term::ANSIColor.send(color.to_sym, string) end end end end string end # Public: Passes .format to Kernel#puts # # string - the text to be formatted # options - The hash of options used for formatting the text: # :color - The color to be passed as a method to # Term::ANSIColor # # # Example # # Coveralls::Output.puts("Hello World", :color => "cyan") # # Returns nil. def puts(string, options = {}) return if silent? (options[:output] || output).puts self.format(string, options) end # Public: Passes .format to Kernel#print # # string - the text to be formatted # options - The hash of options used for formatting the text: # :color - The color to be passed as a method to # Term::ANSIColor # # Example # # Coveralls::Output.print("Hello World!", :color => "underline") # # Returns nil. def print(string, options = {}) return if silent? (options[:output] || output).print self.format(string, options) end def silent? ENV["COVERALLS_SILENT"] || (defined?(@silent) && @silent) end end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/lib/coveralls/api.rb
lib/coveralls/api.rb
require 'json' require 'net/https' require 'tempfile' module Coveralls class API if ENV['COVERALLS_ENDPOINT'] API_HOST = ENV['COVERALLS_ENDPOINT'] API_DOMAIN = ENV['COVERALLS_ENDPOINT'] else API_HOST = ENV['COVERALLS_DEVELOPMENT'] ? "localhost:3000" : "coveralls.io" API_PROTOCOL = ENV['COVERALLS_DEVELOPMENT'] ? "http" : "https" API_DOMAIN = "#{API_PROTOCOL}://#{API_HOST}" end API_BASE = "#{API_DOMAIN}/api/v1" def self.post_json(endpoint, hash) disable_net_blockers! uri = endpoint_to_uri(endpoint) Coveralls::Output.puts("#{ JSON.pretty_generate(hash) }", :color => "green") if ENV['COVERALLS_DEBUG'] Coveralls::Output.puts("[Coveralls] Submitting to #{API_BASE}", :color => "cyan") client = build_client(uri) request = build_request(uri.path, hash) response = client.request(request) response_hash = JSON.load(response.body.to_str) if response_hash['message'] Coveralls::Output.puts("[Coveralls] #{ response_hash['message'] }", :color => "cyan") end if response_hash['url'] Coveralls::Output.puts("[Coveralls] #{ Coveralls::Output.format(response_hash['url'], :color => "underline") }", :color => "cyan") end case response when Net::HTTPServiceUnavailable Coveralls::Output.puts("[Coveralls] API timeout occured, but data should still be processed", :color => "red") when Net::HTTPInternalServerError Coveralls::Output.puts("[Coveralls] API internal error occured, we're on it!", :color => "red") end end private def self.disable_net_blockers! begin require 'webmock' allow = WebMock::Config.instance.allow || [] WebMock::Config.instance.allow = [*allow].push API_HOST rescue LoadError end begin require 'vcr' VCR.send(VCR.version.major < 2 ? :config : :configure) do |c| c.ignore_hosts API_HOST end rescue LoadError end end def self.endpoint_to_uri(endpoint) URI.parse("#{API_BASE}/#{endpoint}") end def self.build_client(uri) client = Net::HTTP.new(uri.host, uri.port) client.use_ssl = true if uri.port == 443 client.verify_mode = OpenSSL::SSL::VERIFY_NONE unless client.respond_to?(:ssl_version=) Net::HTTP.ssl_context_accessor("ssl_version") end client.ssl_version = 'TLSv1' client end def self.build_request(path, hash) request = Net::HTTP::Post.new(path) boundary = rand(1_000_000).to_s request.body = build_request_body(hash, boundary) request.content_type = "multipart/form-data, boundary=#{boundary}" request end def self.build_request_body(hash, boundary) hash = apified_hash(hash) file = hash_to_file(hash) "--#{boundary}\r\n" \ "Content-Disposition: form-data; name=\"json_file\"; filename=\"#{File.basename(file.path)}\"\r\n" \ "Content-Type: text/plain\r\n\r\n" + File.read(file.path) + "\r\n--#{boundary}--\r\n" end def self.hash_to_file(hash) file = nil Tempfile.open(['coveralls-upload', 'json']) do |f| f.write(JSON.dump hash) file = f end File.new(file.path, 'rb') end def self.apified_hash hash config = Coveralls::Configuration.configuration if ENV['COVERALLS_DEBUG'] || Coveralls.testing Coveralls::Output.puts "[Coveralls] Submitting with config:", :color => "yellow" output = JSON.pretty_generate(config).gsub(/"repo_token": ?"(.*?)"/,'"repo_token": "[secure]"') Coveralls::Output.puts output, :color => "yellow" end hash.merge(config) end end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/lib/coveralls/configuration.rb
lib/coveralls/configuration.rb
require 'yaml' require 'securerandom' module Coveralls module Configuration def self.configuration config = { :environment => self.relevant_env, :git => git } yml = self.yaml_config if yml config[:configuration] = yml config[:repo_token] = yml['repo_token'] || yml['repo_secret_token'] end if ENV['COVERALLS_REPO_TOKEN'] config[:repo_token] = ENV['COVERALLS_REPO_TOKEN'] end if ENV['COVERALLS_PARALLEL'] && ENV['COVERALLS_PARALLEL'] != "false" config[:parallel] = true end if ENV['COVERALLS_FLAG_NAME'] config[:flag_name] = ENV['COVERALLS_FLAG_NAME'] end if ENV['TRAVIS'] set_service_params_for_travis(config, yml ? yml['service_name'] : nil) elsif ENV['CIRCLECI'] set_service_params_for_circleci(config) elsif ENV['SEMAPHORE'] set_service_params_for_semaphore(config) elsif ENV['JENKINS_URL'] || ENV['JENKINS_HOME'] set_service_params_for_jenkins(config) elsif ENV['APPVEYOR'] set_service_params_for_appveyor(config) elsif ENV['TDDIUM'] set_service_params_for_tddium(config) elsif ENV['GITLAB_CI'] set_service_params_for_gitlab(config) elsif ENV['COVERALLS_RUN_LOCALLY'] || Coveralls.testing set_service_params_for_coveralls_local(config) end # standardized env vars set_standard_service_params_for_generic_ci(config) if service_name = ENV['COVERALLS_SERVICE_NAME'] config[:service_name] = service_name end config end def self.set_service_params_for_travis(config, service_name) config[:service_job_id] = ENV['TRAVIS_JOB_ID'] config[:service_pull_request] = ENV['TRAVIS_PULL_REQUEST'] unless ENV['TRAVIS_PULL_REQUEST'] == 'false' config[:service_name] = service_name || 'travis-ci' config[:service_branch] = ENV['TRAVIS_BRANCH'] end def self.set_service_params_for_circleci(config) config[:service_name] = 'circleci' config[:service_number] = ENV['CIRCLE_WORKFLOW_ID'] || ENV['CIRCLE_BUILD_NUM'] config[:service_pull_request] = (ENV['CI_PULL_REQUEST'] || "")[/(\d+)$/,1] config[:parallel] = ENV['CIRCLE_NODE_TOTAL'].to_i > 1 config[:service_job_number] = ENV['CIRCLE_NODE_INDEX'] end def self.set_service_params_for_semaphore(config) config[:service_name] = 'semaphore' config[:service_number] = ENV['SEMAPHORE_BUILD_NUMBER'] config[:service_pull_request] = ENV['PULL_REQUEST_NUMBER'] end def self.set_service_params_for_jenkins(config) config[:service_name] = 'jenkins' config[:service_number] = ENV['BUILD_NUMBER'] config[:service_branch] = ENV['BRANCH_NAME'] config[:service_pull_request] = ENV['ghprbPullId'] end def self.set_service_params_for_appveyor(config) config[:service_name] = 'appveyor' config[:service_number] = ENV['APPVEYOR_BUILD_VERSION'] config[:service_branch] = ENV['APPVEYOR_REPO_BRANCH'] config[:commit_sha] = ENV['APPVEYOR_REPO_COMMIT'] repo_name = ENV['APPVEYOR_REPO_NAME'] config[:service_build_url] = 'https://ci.appveyor.com/project/%s/build/%s' % [repo_name, config[:service_number]] end def self.set_service_params_for_tddium(config) config[:service_name] = 'tddium' config[:service_number] = ENV['TDDIUM_SESSION_ID'] config[:service_job_number] = ENV['TDDIUM_TID'] config[:service_pull_request] = ENV['TDDIUM_PR_ID'] config[:service_branch] = ENV['TDDIUM_CURRENT_BRANCH'] config[:service_build_url] = "https://ci.solanolabs.com/reports/#{ENV['TDDIUM_SESSION_ID']}" end def self.set_service_params_for_gitlab(config) config[:service_name] = 'gitlab-ci' config[:service_number] = ENV['CI_PIPELINE_ID'] config[:service_job_number] = ENV['CI_BUILD_NAME'] config[:service_job_id] = ENV['CI_BUILD_ID'] config[:service_branch] = ENV['CI_BUILD_REF_NAME'] config[:service_pull_request] = ENV['CI_MERGE_REQUEST_IID'] config[:commit_sha] = ENV['CI_BUILD_REF'] end def self.set_service_params_for_coveralls_local(config) config[:service_job_id] = nil config[:service_name] = 'coveralls-ruby' config[:service_event_type] = 'manual' end def self.set_standard_service_params_for_generic_ci(config) config[:service_name] ||= ENV['CI_NAME'] config[:service_number] ||= ENV['CI_BUILD_NUMBER'] config[:service_job_id] ||= ENV['CI_JOB_ID'] config[:service_build_url] ||= ENV['CI_BUILD_URL'] config[:service_branch] ||= ENV['CI_BRANCH'] config[:service_pull_request] ||= (ENV['CI_PULL_REQUEST'] || "")[/(\d+)$/,1] end def self.yaml_config if self.configuration_path && File.exist?(self.configuration_path) YAML::load_file(self.configuration_path) end end def self.configuration_path File.expand_path(File.join(self.root, ".coveralls.yml")) if self.root end def self.root pwd end def self.pwd Dir.pwd end def self.simplecov_root if defined?(::SimpleCov) ::SimpleCov.root end end def self.rails_root Rails.root.to_s rescue nil end def self.git hash = {} Dir.chdir(root) do hash[:head] = { :id => ENV.fetch("GIT_ID", `git log -1 --pretty=format:'%H'`), :author_name => ENV.fetch("GIT_AUTHOR_NAME", `git log -1 --pretty=format:'%aN'`), :author_email => ENV.fetch("GIT_AUTHOR_EMAIL", `git log -1 --pretty=format:'%ae'`), :committer_name => ENV.fetch("GIT_COMMITTER_NAME", `git log -1 --pretty=format:'%cN'`), :committer_email => ENV.fetch("GIT_COMMITTER_EMAIL", `git log -1 --pretty=format:'%ce'`), :message => ENV.fetch("GIT_MESSAGE", `git log -1 --pretty=format:'%s'`) } # Branch hash[:branch] = ENV.fetch("GIT_BRANCH", `git rev-parse --abbrev-ref HEAD`) # Remotes remotes = nil begin remotes = `git remote -v`.split(/\n/).map do |remote| splits = remote.split(" ").compact {:name => splits[0], :url => splits[1]} end.uniq rescue end hash[:remotes] = remotes end hash rescue Exception => e Coveralls::Output.puts "Coveralls git error:", :color => "red" Coveralls::Output.puts e.to_s, :color => "red" nil end def self.relevant_env hash = { :pwd => self.pwd, :rails_root => self.rails_root, :simplecov_root => simplecov_root, :gem_version => VERSION } hash.merge! begin if ENV['TRAVIS'] { :travis_job_id => ENV['TRAVIS_JOB_ID'], :travis_pull_request => ENV['TRAVIS_PULL_REQUEST'], :branch => ENV['TRAVIS_BRANCH'] } elsif ENV['CIRCLECI'] { :circleci_build_num => ENV['CIRCLE_BUILD_NUM'], :branch => ENV['CIRCLE_BRANCH'], :commit_sha => ENV['CIRCLE_SHA1'] } elsif ENV['JENKINS_URL'] { :jenkins_build_num => ENV['BUILD_NUMBER'], :jenkins_build_url => ENV['BUILD_URL'], :branch => ENV['GIT_BRANCH'], :commit_sha => ENV['GIT_COMMIT'] } elsif ENV['SEMAPHORE'] { :branch => ENV['BRANCH_NAME'], :commit_sha => ENV['REVISION'] } else {} end end hash end end end
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
lemurheavy/coveralls-ruby
https://github.com/lemurheavy/coveralls-ruby/blob/affba6ec6c49f74a38ce98e646063a84d62f80ea/lib/coveralls/rake/task.rb
lib/coveralls/rake/task.rb
require 'rake' require 'rake/tasklib' module Coveralls class RakeTask < ::Rake::TaskLib include ::Rake::DSL if defined?(::Rake::DSL) def initialize(*args, &task_block) namespace :coveralls do desc "Push latest coverage results to Coveralls.io" task :push do require 'coveralls' Coveralls.push! end end end # initialize end # class end # module
ruby
MIT
affba6ec6c49f74a38ce98e646063a84d62f80ea
2026-01-04T17:47:03.441275Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true if ENV["COVERAGE"] == "true" require "simplecov" require "coveralls" SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ]) SimpleCov.start do command_name "spec" add_filter "spec" end end require "necromancer" RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true expectations.max_formatted_output_length = nil end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end # Limits the available syntax to the non-monkey patched syntax that is recommended. config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true if config.files_to_run.one? config.default_formatter = "doc" end config.profile_examples = 2 config.order = :random Kernel.srand config.seed end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/can_spec.rb
spec/unit/can_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer, "can?" do it "checks if conversion is possible" do converter = described_class.new expect(converter.can?(:string, :integer)).to eq(true) expect(converter.can?(:unknown, :integer)).to eq(false) end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/new_spec.rb
spec/unit/new_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer, "#new" do subject(:converter) { described_class.new } it "creates context" do expect(converter).to be_a(Necromancer::Context) end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/inspect_spec.rb
spec/unit/inspect_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer, ".inspect" do subject(:converter) { described_class.new } it "inspects converter instance" do expect(converter.inspect).to eq( "#<Necromancer::Context@#{converter.object_id} " \ "@config=#{converter.configuration}>" ) end it "inspects conversion target" do conversion = converter.convert(11) expect(conversion.inspect).to eq( "#<Necromancer::ConversionTarget@#{conversion.object_id} " \ "@object=11, @source=integer>" ) end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/register_spec.rb
spec/unit/register_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer, ".register" do it "allows ro register converter" do converter = described_class.new stub_const("UpcaseConverter", Struct.new(:source, :target) do def call(value, **_options) value.to_s.upcase end end) upcase_converter = UpcaseConverter.new(:string, :upcase) expect(converter.register(upcase_converter)).to eq(true) expect(converter.convert("magic").to(:upcase)).to eq("MAGIC") end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/convert_spec.rb
spec/unit/convert_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer, ".convert" do subject(:converter) { described_class.new } it "indicates inability to perform the requested conversion" do expect { converter.convert(:foo).to(:float) }.to raise_error(Necromancer::NoTypeConversionAvailableError, /Conversion 'symbol->float' unavailable/) end it "allows for module level convert call" do expect(Necromancer.convert("1,2,3").to(:array)).to eq(%w[1 2 3]) end it "allows replacing #to with #>> call" do expect(converter.convert("1,2,3") >> :integers).to eq([1, 2, 3]) end it "allows to specify object as conversion target" do expect(converter.convert("1,2,3") >> []).to eq(%w[1 2 3]) end it "allows to specify class as conversion target" do expect(converter.convert("1,2,3") >> Array).to eq(%w[1 2 3]) end context "when array" do it "converts string to array" do expect(converter.convert("1,2,3").to(:array)).to eq(%w[1 2 3]) end it "converts string to array of booleans" do expect(converter.convert("t,f,t").to(:booleans)).to eq([true, false, true]) expect(converter.convert("t,f,t").to(:bools)).to eq([true, false, true]) end it "converts string to array of integers" do expect(converter.convert("1,2,3").to(:integers)).to eq([1, 2, 3]) expect(converter.convert("1,2,3").to(:ints)).to eq([1, 2, 3]) end it "converts string to array of numerics" do expect(converter.convert("1,2.0,3").to(:numerics)).to eq([1, 2.0, 3]) expect(converter.convert("1,2.0,3").to(:nums)).to eq([1, 2.0, 3]) end it "converts array to numerics " do conversion = converter.convert(["1", "2.3", "3.0"]).to(:numerics) expect(conversion).to eq([1, 2.3, 3.0]) conversion = converter.convert(["1", "2.3", "3.0"]).to(:nums) expect(conversion).to eq([1, 2.3, 3.0]) end it "converts array to array of booleans" do expect(converter.convert(%w[t no]).to(:booleans)).to eq([true, false]) expect(converter.convert(%w[t no]).to(:bools)).to eq([true, false]) end it "converts object to array" do expect(converter.convert({ x: 1 }).to(:array)).to eq([[:x, 1]]) end it "fails to convert in strict mode" do expect { converter.convert(["1", "2.3", false]).to(:numerics, strict: true) }.to raise_error(Necromancer::ConversionTypeError) end end context "when hash" do it "converts hash to hash" do conversion = converter.convert({ a: 1, b: 2, c: 3 }).to(:hash) expect(conversion).to eq({ a: 1, b: 2, c: 3 }) end it "converts string to hash" do conversion = converter.convert("a:1 b:2 c:3").to(:hash) expect(conversion).to eq({ a: "1", b: "2", c: "3" }) end it "converts string to integer hash" do conversion = converter.convert("a:1 b:2 c:3").to(:int_hash) expect(conversion).to eq({ a: 1, b: 2, c: 3 }) end it "converts string to float hash" do conversion = converter.convert("a:1 b:2 c:3").to(:float_hash) expect(conversion).to eq({ a: 1.0, b: 2.0, c: 3.0 }) end it "converts string to numeric hash" do conversion = converter.convert("a:1 b:2.0 c:3").to(:numeric_hash) expect(conversion).to eq({ a: 1, b: 2.0, c: 3 }) end it "converts string to boolean hash" do conversion = converter.convert("a:t b:f c:t").to(:boolean_hash) expect(conversion).to eq({ a: true, b: false, c: true }) end it "converts string to bool hash" do conversion = converter.convert("a:t b:f c:t").to(:bool_hash) expect(conversion).to eq({ a: true, b: false, c: true }) end end context "when numeric" do it "converts string to integer" do expect(converter.convert("1").to(:integer)).to eq(1) end it "allows for block for conversion method" do expect(converter.convert { "1" }.to(:integer)).to eq(1) end it "convers integer to string" do expect(converter.convert(1).to(:string)).to eq("1") end it "allows for null type conversion" do expect(converter.convert(1).to(:integer)).to eq(1) end it "raises error when in strict mode" do expect { converter.convert("1a").to(:integer, strict: true) }.to raise_error(Necromancer::ConversionTypeError) end it "doesn't raise error when in non-strict mode" do expect(converter.convert("1").to(:integer, strict: false)).to eql(1) end it "converts string to float" do expect(converter.convert("1.0").to(:float)).to eql(1.0) end it "converts string to numeric" do expect(converter.convert("1.0").to(:numeric)).to eql(1.0) end end context "when boolean" do it "converts boolean to boolean" do expect(converter.convert(true).to(:boolean)).to eq(true) end it "converts string to boolean" do expect(converter.convert("yes").to(:boolean)).to eq(true) end it "converts integer to boolean" do expect(converter.convert(0).to(:boolean)).to eq(false) end it "converts boolean to integer" do expect(converter.convert(true).to(:integer)).to eq(1) end end context "when range" do it "converts string to range" do expect(converter.convert("1-10").to(:range)).to eq(1..10) end end context "when datetime" do it "converts string to date" do expect(converter.convert("2014-12-07").to(:date)) .to eq(Date.parse("2014-12-07")) end it "converts string to datetime" do expect(converter.convert("2014-12-07 17:35:44").to(:datetime)) .to eq(DateTime.parse("2014-12-07 17:35:44")) end it "converts string to time" do expect(converter.convert("12:30").to(:time)) .to eq(Time.parse("12:30")) end end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/config_spec.rb
spec/unit/config_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer, "config" do it "configures global settings per instance" do converter = described_class.new converter.configure do |config| config.strict false end expect(converter.convert("1.2.3").to(:array)).to eq(["1.2.3"]) converter.configure do |config| config.strict true end expect { converter.convert("1.2.3").to(:array) }.to raise_error(Necromancer::ConversionTypeError) end it "configures global settings through instance block" do converter = described_class.new do |config| config.strict true end expect(converter.configuration.strict).to eq(true) expect { converter.convert("1.2.3").to(:array) }.to raise_error(Necromancer::ConversionTypeError) end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/converters/array_spec.rb
spec/unit/converters/array_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::ArrayConverters, "#call" do describe ":string -> :array" do subject(:converter) { described_class::StringToArrayConverter.new(:string, :array) } { "" => [], "123" => %w[123], "1,2,3" => %w[1 2 3], "1-2-3" => %w[1 2 3], " 1 - 2 - 3 " => [" 1 ", " 2 ", " 3 "], "1 , 2 , 3" => ["1 ", " 2 ", " 3"], "1.2,2.3,3.4" => %w[1.2 2.3 3.4], "a,b,c" => %w[a b c], "a-b-c" => %w[a b c], "aa a,b bb,c c c" => %w[aa\ a b\ bb c\ c\ c] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert empty string to array in strict mode" do expect { converter.("unknown", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'unknown' could not be converted from `string` into `array`" ) end end describe ":string -> :booleans" do subject(:converter) { described_class::StringToBooleanArrayConverter.new } { "t,f,t" => [true, false, true], "yes,no,Y" => [true, false, true], "1-0-FALSE" => [true, false, false] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert in strict mode" do expect { converter.("yes,unknown", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'unknown' could not be converted from `string` into `boolean`" ) end end describe ":string -> :integers/:ints" do subject(:converter) { described_class::StringToIntegerArrayConverter.new } { "1,2,3" => [1, 2, 3], "1.2, 2.3, 3.4" => [1, 2, 3] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert in strict mode" do expect { converter.("1,unknown", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'unknown' could not be converted from `string` into `integer`" ) end end describe ":string -> :floats" do subject(:converter) { described_class::StringToFloatArrayConverter.new } { "1,2,3" => [1.0, 2.0, 3.0], "1.2, 2.3, 3.4" => [1.2, 2.3, 3.4] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert in strict mode" do expect { converter.("1,unknown", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'unknown' could not be converted from `string` into `float`" ) end end describe ":string -> :numerics/:nums" do subject(:converter) { described_class::StringToNumericArrayConverter.new } { "1,2.0,3" => [1, 2.0, 3], "1.2, 2.3, 3.4" => [1.2, 2.3, 3.4] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert in strict mode" do expect { converter.("1,unknown", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'unknown' could not be converted from `string` into `numeric`" ) end end describe ":array -> :booleans/:bools" do subject(:converter) { described_class::ArrayToBooleanArrayConverter.new(:array, :boolean) } { %w[t f yes no] => [true, false, true, false], %w[t no 5] => [true, false, "5"] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert `['t', 'no', 5]` to boolean array in strict mode" do expect { converter.(["t", "no", 5], strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'5' could not be converted from `string` into `boolean`" ) end end describe ":array -> :integers" do subject(:converter) { described_class::ArrayToIntegerArrayConverter.new } { %w[1 2 3] => [1, 2, 3], %w[1.2 2.3 3.4] => [1, 2, 3] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert `['1','2.3']` to integer array in strict mode" do expect { converter.(["1", "2.3"], strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'2.3' could not be converted from `string` into `integer`" ) end end describe ":array -> :floats" do subject(:converter) { described_class::ArrayToFloatArrayConverter.new } { %w[1 2 3] => [1.0, 2.0, 3.0], %w[1.2 2.3 3.4] => [1.2, 2.3, 3.4] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert `['1','2.3',false]` to float array in strict mode" do expect { converter.(["1", "2.3", false], strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'false' could not be converted from `string` into `float`" ) end end describe ":array -> :numerics/:nums" do subject(:converter) { described_class::ArrayToNumericArrayConverter.new(:array, :numerics) } { %w[1 2.3 3.0] => [1, 2.3, 3.0], %w[1 2.3 false] => [1, 2.3, "false"] }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert `['1','2.3',false]` to numeric array in strict mode" do expect { converter.(["1", "2.3", false], strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'false' could not be converted from `string` into `numeric`" ) end end describe ":array -> :set" do subject(:converter) { described_class::ArrayToSetConverter.new(:array, :set) } it "converts `[:x,:y,:x,1,2,1]` to set" do expect(converter.([:x, :y, :x, 1, 2, 1])).to eql(Set[:x, :y, 1, 2]) end it "fails to convert `1` to set" do expect { converter.(1, strict: true) }.to raise_error(Necromancer::ConversionTypeError) end end describe ":object -> :array" do subject(:converter) { described_class::ObjectToArrayConverter.new(:object, :array) } it "converts nil to array" do expect(converter.(nil)).to eq([]) end it "converts custom object to array" do stub_const("Custom", Class.new do def to_ary %i[x y] end end) custom = Custom.new expect(converter.(custom)).to eq(%i[x y]) end end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/converters/range_spec.rb
spec/unit/converters/range_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::RangeConverters, "#call" do describe ":string -> :range" do subject(:converter) { described_class::StringToRangeConverter.new } { "" => "", "a" => "a", "1" => 1..1, "1.0" => 1.0..1.0, "1..10" => 1..10, "1.0..10.0" => 1.0..10.0, "1-10" => 1..10, "1 , 10" => 1..10, "1...10" => 1...10, "1 . . 10" => 1..10, "-1..10" => -1..10, "1..-10" => 1..-10, "a..z" => "a".."z", "a . . . z" => "a"..."z", "a-z" => "a".."z", "A , Z" => "A".."Z" }.each do |actual, expected| it "converts #{actual.inspect} to range type" do expect(converter.(actual)).to eql(expected) end end it "raises error for empty string in strict mode" do expect { converter.("", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/converters/date_time_spec.rb
spec/unit/converters/date_time_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::DateTimeConverters, "#call" do describe ":string -> :date" do subject(:converter) { described_class::StringToDateConverter.new(:string, :date) } { "" => "", "1-1-2015" => Date.parse("2015/01/01"), "2014/12/07" => Date.parse("2014/12/07"), "2014-12-07" => Date.parse("2014/12/07") }.each do |actual, expected| it "converts #{actual.inspect} to range type" do expect(converter.(actual)).to eql(expected) end end it "fails to convert in strict mode" do expect { converter.("2014 - 12 - 07", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'2014 - 12 - 07' could not be converted from `string` into `date`" ) end end describe ":string -> :datetime" do subject(:converter) { described_class::StringToDateTimeConverter.new(:string, :datetime) } { "" => "", "2014/12/07" => DateTime.parse("2014/12/07"), "2014-12-07" => DateTime.parse("2014-12-07"), "7th December 2014" => DateTime.parse("2014-12-07"), "7th December 2014 17:19:44" => DateTime.parse("2014-12-07 17:19:44") }.each do |actual, expected| it "converts #{actual.inspect} to range type" do expect(converter.(actual)).to eql(expected) end end it "fails to convert in strict mode" do expect { converter.("2014 - 12 - 07", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end end describe ":string -> :time" do subject(:converter) { described_class::StringToTimeConverter.new(:string, :time) } { "" => "", "01/01/2015" => Time.parse("01/01/2015"), "01/01/2015 08:35" => Time.parse("01/01/2015 08:35"), "12:35" => Time.parse("12:35") }.each do |actual, expected| it "converts #{actual.inspect} to range type" do expect(converter.(actual)).to eql(expected) end end it "fails to convert in strict mode" do expect { converter.("11-13-2015", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/converters/numeric_spec.rb
spec/unit/converters/numeric_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::NumericConverters, "#call" do describe ":string -> :float" do subject(:converter) { described_class::StringToFloatConverter.new(:string, :float) } { "" => 0.0, "1" => 1.0, "+1" => 1.0, "1.2a" => 1.2, "-1" => -1.0, "1e1" => 10.0, "1e-1" => 0.1, "-1e1" => -10.0, "-1e-1" => -0.1, "1.0" => 1.0, "1.0e+1" => 10.0, "1.0e-1" => 0.1, "-1.0e+1" => -10.0, "-1.0e-1" => -0.1, ".1" => 0.1, ".1e+1" => 1.0, ".1e-1" => 0.01, "-.1e+1" => -1.0, "-.1e-1" => -0.01, " 1. 10 " => 1.0, " 1.0" => 1.0, " .1 " => 0.1, " -1.1 " => -1.1, " -1 . 1" => -1.0 }.each do |actual, expected| it "converts '#{actual}' to float value" do expect(converter.(actual)).to eql(expected) end end it "raises error for empty string in strict mode" do expect { converter.("", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end it "fails to convert '1.2a' in strict mode" do expect { converter.("1.2a", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'1.2a' could not be converted from `string` into `float`" ) end end describe ":string -> :integer" do subject(:converter) { described_class::StringToIntegerConverter.new(:string, :integer) } { "" => 0, "1" => 1, "1ab" => 1, "+1" => 1, "-1" => -1, "1e+1" => 1, "+1e-1" => 1, "-1e1" => -1, "-1e-1" => -1, "1.0" => 1, "1.0e+1" => 1, "1.0e-1" => 1, "-1.0e+1" => -1, "-1.0e-1" => -1, ".1" => 0, ".1e+1" => 0, ".1e-1" => 0, "-.1e+1" => 0, "-.1e-1" => 0, " 1 00" => 1, " 1 " => 1, " -1 " => -1 }.each do |actual, expected| it "converts '#{actual}' to float value" do expect(converter.(actual)).to eql(expected) end end it "raises error for empty string in strict mode" do expect { converter.("", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end it "raises error for float in strict mode" do expect { converter.("1.2", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end it "raises error for mixed string in strict mode" do expect { converter.("1abc", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end end describe ":string -> :numeric" do subject(:converter) { described_class::StringToNumericConverter.new(:string, :numeric) } { "" => 0, "1" => 1, "+1" => 1, "-1" => -1, "1e1" => 10.0, "1e-1" => 0.1, "-1e1" => -10.0, "-1e-1" => -0.1, "1.0" => 1.0, "1.0e+1" => 10.0, "1.0e-1" => 0.1, "-1.0e+1" => -10.0, "-1.0e-1" => -0.1, ".1" => 0.1, ".1e+1" => 1.0, ".1e-1" => 0.01, "-.1e+1" => -1.0, "-.1e-1" => -0.01, " 1 00" => 1, " 1 " => 1, " -1 " => -1, " 1. 10 " => 1.0, " 1.0" => 1.0, " .1 " => 0.1, " -1.1 " => -1.1, " -1 . 1" => -1.0 }.each do |actual, expected| it "converts '#{actual}' to '#{expected}'" do expect(converter.(actual)).to eql(expected) end end end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/converters/hash_spec.rb
spec/unit/converters/hash_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::HashConverters, "#call" do describe ":string -> :hash" do subject(:converter) { described_class::StringToHashConverter.new } { "a=1" => { a: "1" }, "a=1&b=2" => { a: "1", b: "2" }, "a= & b=2" => { a: "", b: "2" }, "a=1 & b=2 & a=3" => { a: %w[1 3], b: "2" }, "a:1 b:2" => { a: "1", b: "2" }, "a:1 b:2 a:3" => { a: %w[1 3], b: "2" } }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end end describe ":string -> :int_hash" do subject(:converter) { described_class::StringToIntegerHashConverter.new } { "a=1 & b=2 & a=3" => { a: [1, 3], b: 2 }, "a:1 b:2 c:3" => { a: 1, b: 2, c: 3 }, }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert '1.2o' value in strict mode" do expect { converter.("a=1.2o", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'1.2o' could not be converted from `string` into `integer`" ) end end describe ":string -> :float_hash" do subject(:converter) { described_class::StringToFloatHashConverter.new } { "a=1 & b=2 & a=3" => { a: [1.0, 3.0], b: 2.0 }, "a:1 b:2 c:3" => { a: 1.0, b: 2.0, c: 3.0 } }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eql(obj) end end it "fails to convert '1.2o' value in strict mode" do expect { converter.("a=1.2o", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'1.2o' could not be converted from `string` into `float`" ) end end describe ":string -> :numeric_hash" do subject(:converter) { described_class::StringToNumericHashConverter.new } { "a=1 & b=2.0 & a=3.0" => { a: [1, 3.0], b: 2.0 }, "a:1 b:2.0 c:3.0" => { a: 1, b: 2.0, c: 3.0 } }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eql(obj) end end it "fails to convert '1.2o' value in strict mode" do expect { converter.("a=1.2o", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'1.2o' could not be converted from `string` into `numeric`" ) end end describe ":string -> :bool_hash" do subject(:converter) { described_class::StringToBooleanHashConverter.new } { "a=t & b=t & a=f" => { a: [true, false], b: true }, "a:yes b:no c:t" => { a: true, b: false, c: true } }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eql(obj) end end it "fails to convert '1.2o' value in strict mode" do expect { converter.("a=1.2", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'1.2' could not be converted from `string` into `boolean`" ) end end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/converters/boolean_spec.rb
spec/unit/converters/boolean_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::BooleanConverters, "#call" do describe ":string -> :boolean" do subject(:converter) { described_class::StringToBooleanConverter.new(:string, :boolean) } it "passes through boolean value" do expect(converter.(true)).to eq(true) end %w[true TRUE t T 1 y Y YES yes on ON].each do |value| it "converts '#{value}' to true value" do expect(converter.(value)).to eq(true) end end %w[false FALSE f F 0 n N NO No no off OFF].each do |value| it "converts '#{value}' to false value" do expect(converter.(value)).to eq(false) end end it "raises error for empty string strict mode" do expect { converter.("", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end it "fails to convert unkonwn value FOO" do expect { converter.("FOO", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end end describe ":boolean -> :integer" do subject(:converter) { described_class::BooleanToIntegerConverter.new(:boolean, :integer) } { true => 1, false => 0, "unknown" => "unknown" }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert in strict mode" do expect { converter.("unknown", strict: true) }.to raise_error( Necromancer::ConversionTypeError, "'unknown' could not be converted from `boolean` into `integer`" ) end end describe ":integer -> :boolean" do subject(:converter) { described_class::IntegerToBooleanConverter.new } { 1 => true, 0 => false, "unknown" => "unknown" }.each do |input, obj| it "converts #{input.inspect} to #{obj.inspect}" do expect(converter.(input)).to eq(obj) end end it "fails to convert in strict mode" do expect { converter.("1", strict: true) }.to raise_error(Necromancer::ConversionTypeError) end end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/conversions/register_spec.rb
spec/unit/conversions/register_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::Conversions, ".register" do it "allows to register converter" do context = described_class.new converter = double(:converter, { source: :string, target: :numeric }) expect(context.register(converter)).to eq(true) expect(context[:string, :numeric]).to eq(converter) end it "allows to register converter with no source" do context = described_class.new converter = double(:converter, { source: nil, target: :numeric }) expect(context.register(converter)).to eq(true) expect(context[:none, :numeric]).to eq(converter) end it "allows to register converter with no target" do context = described_class.new converter = double(:converter, { source: :string, target: nil }) expect(context.register(converter)).to eq(true) expect(context[:string, :none]).to eq(converter) end it "allows to register anonymous converter" do conversions = described_class.new conversions.register do |c| c.source = :string c.target = :upcase c.convert = ->(value) { value.to_s.upcase } end expect(conversions[:string, :upcase].("magic")).to eq("MAGIC") end it "allows to register anonymous converter with class names" do conversions = described_class.new conversions.register do |c| c.source = String c.target = Array c.convert = ->(value) { Array(value) } end expect(conversions[String, Array].("magic")).to eq(["magic"]) end it "allows to register custom converter" do conversions = described_class.new stub_const("UpcaseConverter", Struct.new(:source, :target) do def call(value) value.to_s.upcase end end) upcase_converter = UpcaseConverter.new(:string, :upcase) expect(conversions.register(upcase_converter)).to be(true) expect(conversions[:string, :upcase].("magic")).to eq("MAGIC") end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/conversions/fetch_spec.rb
spec/unit/conversions/fetch_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::Conversions, "#fetch" do it "retrieves conversion given source & target" do converter = double(:converter) conversions = described_class.new nil, { "string->array" => converter } expect(conversions["string", "array"]).to eq(converter) end it "fails to find conversion" do conversions = described_class.new expect { conversions["string", "array"] }.to raise_error(Necromancer::NoTypeConversionAvailableError) end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/conversions/to_hash_spec.rb
spec/unit/conversions/to_hash_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::Conversions, "#to_hash" do it "exports default conversions to hash" do conversions = Necromancer::Conversions.new expect(conversions.to_hash).to eq({}) conversions.load expect(conversions.to_hash.keys.sort).to eq([ "array->array", "array->booleans", "array->bools", "array->floats", "array->integers", "array->ints", "array->numerics", "array->nums", "boolean->boolean", "boolean->integer", "date->date", "datetime->datetime", "float->float", "hash->array", "hash->hash", "integer->boolean", "integer->integer", "integer->string", "object->array", "range->range", "string->array", "string->bool_hash", "string->boolean", "string->boolean_hash", "string->booleans", "string->bools", "string->date", "string->datetime", "string->float", "string->float_hash", "string->floats", "string->hash", "string->int_hash", "string->integer", "string->integer_hash", "string->integers", "string->ints", "string->num_hash", "string->numeric", "string->numeric_hash", "string->numerics", "string->nums", "string->range", "string->time", "time->time" ]) end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/spec/unit/configuration/new_spec.rb
spec/unit/configuration/new_spec.rb
# frozen_string_literal: true RSpec.describe Necromancer::Configuration, ".new" do subject(:config) { described_class.new } it { is_expected.to respond_to(:strict=) } it { is_expected.to respond_to(:copy=) } it "is in non-strict mode by default" do expect(config.strict).to eq(false) end it "is in copy mode by default" do expect(config.copy).to eq(true) end it "allows to set strict through method" do config.strict true expect(config.strict).to eq(true) end it "allows to set copy mode through method" do config.copy false expect(config.strict).to eq(false) end end
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer.rb
lib/necromancer.rb
# frozen_string_literal: true require_relative "necromancer/context" require_relative "necromancer/version" module Necromancer # Raised when cannot conver to a given type ConversionTypeError = Class.new(StandardError) # Raised when conversion type is not available NoTypeConversionAvailableError = Class.new(StandardError) # Create a conversion instance # # @example # converter = Necromancer.new # # @return [Context] # # @api private def new(&block) Context.new(&block) end module_function :new # Convenience to directly call conversion # # @example # Necromancer.convert("1").to(:integer) # # => 1 # # @return [ConversionTarget] # # @api public def convert(*args, &block) Context.new.convert(*args, &block) end module_function :convert end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/version.rb
lib/necromancer/version.rb
# frozen_string_literal: true module Necromancer VERSION = "0.7.0" end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/converter.rb
lib/necromancer/converter.rb
# frozen_string_literal: true require_relative "configuration" module Necromancer # Abstract converter used internally as a base for other converters # # @api private class Converter # Create an abstract converter # # @param [Object] source # the source object type # # @param [Object] target # the target object type # # @api public def initialize(source = nil, target = nil) @source = source if source @target = target if target @config ||= Configuration.new end # Run converter # # @api private def call(*) raise NotImplementedError end # Creates anonymous converter # # @api private def self.create(&block) Class.new(self) do define_method(:initialize) { |*a| block.(self, *a) } define_method(:call) { |value| convert.(value) } end.new end # Fail with conversion type error # # @param [Object] value # the value that cannot be converted # # @api private def raise_conversion_type(value) raise ConversionTypeError, "'#{value}' could not be converted " \ "from `#{source}` into `#{target}`" end attr_accessor :source attr_accessor :target attr_accessor :convert # protected attr_reader :config end # Converter end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/null_converter.rb
lib/necromancer/null_converter.rb
# frozen_string_literal: true require_relative "converter" module Necromancer # A pass through converter class NullConverter < Converter def call(value, strict: config.strict) value end end # NullConverter end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/conversions.rb
lib/necromancer/conversions.rb
# frozen_string_literal: true require_relative "configuration" require_relative "converter" require_relative "converters/array" require_relative "converters/boolean" require_relative "converters/date_time" require_relative "converters/hash" require_relative "converters/numeric" require_relative "converters/range" module Necromancer # Represents the context used to configure various converters # and facilitate type conversion # # @api public class Conversions DELIMITER = "->" # Creates a new conversions map # # @example # conversion = Necromancer::Conversions.new # # @api public def initialize(configuration = Configuration.new, map = {}) @configuration = configuration @converter_map = map.dup end # Load converters # # @api private def load ArrayConverters.load(self) BooleanConverters.load(self) DateTimeConverters.load(self) HashConverters.load(self) NumericConverters.load(self) RangeConverters.load(self) end # Retrieve converter for source and target # # @param [Object] source # the source of conversion # # @param [Object] target # the target of conversion # # @return [Converter] # the converter for the source and target # # @api public def [](source, target) key = "#{source}#{DELIMITER}#{target}" converter_map[key] || converter_map["object#{DELIMITER}#{target}"] || raise_no_type_conversion_available(key) end alias fetch [] # Register a converter # # @example with simple object # conversions.register NullConverter.new(:array, :array) # # @example with block # conversions.register do |c| # c.source = :array # c.target = :array # c.convert = -> { |val, options| val } # end # # @api public def register(converter = nil, &block) converter ||= Converter.create(&block) key = generate_key(converter) converter = add_config(converter, @configuration) return false if converter_map.key?(key) converter_map[key] = converter true end # Export all the conversions as hash # # @return [Hash[String, String]] # # @api public def to_hash converter_map.dup end protected # Fail with conversion error # # @api private def raise_no_type_conversion_available(key) raise NoTypeConversionAvailableError, "Conversion '#{key}' unavailable." end # @api private def generate_key(converter) parts = [] parts << (converter.source ? converter.source.to_s : "none") parts << (converter.target ? converter.target.to_s : "none") parts.join(DELIMITER) end # Inject config into converter # # @api private def add_config(converter, config) converter.instance_exec(:"@config") do |var| instance_variable_set(var, config) end converter end # Map of type and conversion # # @return [Hash] # # @api private attr_reader :converter_map end # Conversions end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/configuration.rb
lib/necromancer/configuration.rb
# frozen_string_literal: true module Necromancer # A global configuration for converters. # # Used internally by {Necromancer::Context}. # # @api private class Configuration # Configure global strict mode # # @api public attr_writer :strict # Configure global copy mode # # @api public attr_writer :copy # Create a configuration # # @api private def initialize @strict = false @copy = true end # Set or get strict mode # # @return [Boolean] # # @api public def strict(value = (not_set = true)) not_set ? @strict : (self.strict = value) end # Set or get copy mode # # @return [Boolean] # # @api public def copy(value = (not_set = true)) not_set ? @copy : (self.copy = value) end end # Configuration end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/context.rb
lib/necromancer/context.rb
# frozen_string_literal: true require "forwardable" require_relative "configuration" require_relative "conversions" require_relative "conversion_target" module Necromancer # A class used by Necromancer to provide user interace # # @api public class Context extend Forwardable def_delegators :"@conversions", :register # Create a context. # # @api private def initialize(&block) block.(configuration) if block_given? @conversions = Conversions.new(configuration) @conversions.load end # The configuration object. # # @example # converter = Necromancer.new # converter.configuration.strict = true # # @return [Necromancer::Configuration] # # @api public def configuration @configuration ||= Configuration.new end # Yields global configuration to a block. # # @yield [Necromancer::Configuration] # # @example # converter = Necromancer.new # converter.configure do |config| # config.strict true # end # # @api public def configure yield configuration if block_given? end # Converts the object # @param [Object] object # any object to be converted # # @api public def convert(object = ConversionTarget::UndefinedValue, &block) ConversionTarget.for(conversions, object, block) end # Check if this converter can convert source to target # # @param [Object] source # the source class # @param [Object] target # the target class # # @return [Boolean] # # @api public def can?(source, target) !conversions[source, target].nil? rescue NoTypeConversionAvailableError false end # Inspect this context # # @api public def inspect %(#<#{self.class}@#{object_id} @config=#{configuration}>) end protected attr_reader :conversions end # Context end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/conversion_target.rb
lib/necromancer/conversion_target.rb
# frozen_string_literal: true module Necromancer # A class responsible for wrapping conversion target # # @api private class ConversionTarget # Used as a stand in for lack of value # @api private UndefinedValue = Module.new # @api private def initialize(conversions, object) @object = object @conversions = conversions end # @api private def self.for(context, value, block) if UndefinedValue.equal?(value) unless block raise ArgumentError, "You need to pass either argument or a block to `convert`." end new(context, block.call) elsif block raise ArgumentError, "You cannot pass both an argument and a block to `convert`." else new(context, value) end end # Allows to specify conversion source type # # @example # converter.convert("1").from(:string).to(:numeric) # => 1 # # @return [ConversionType] # # @api public def from(source) @source = source self end # Runs a given conversion # # @example # converter.convert("1").to(:numeric) # => 1 # # @example # converter.convert("1") >> Integer # => 1 # # @return [Object] # the converted target type # # @api public def to(target, options = {}) conversion = conversions[source || detect(object, false), detect(target)] conversion.call(object, **options) end alias >> to # Inspect this conversion # # @api public def inspect %(#<#{self.class}@#{object_id} @object=#{object}, @source=#{detect(object)}>) end protected # Detect object type and coerce into known key type # # @param [Object] object # # @api private def detect(object, symbol_as_object = true) case object when TrueClass, FalseClass then :boolean when Integer then :integer when Class then object.name.downcase else if object.is_a?(Symbol) && symbol_as_object object else object.class.name.downcase end end end attr_reader :object attr_reader :conversions attr_reader :source end # ConversionTarget end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/converters/range.rb
lib/necromancer/converters/range.rb
# frozen_string_literal: true require_relative "../converter" require_relative "../null_converter" module Necromancer # Container for Range converter classes module RangeConverters SINGLE_DIGIT_MATCHER = /^(?<digit>-?\d+(\.\d+)?)$/.freeze DIGIT_MATCHER = /^(?<open>-?\d+(\.\d+)?) \s*(?<sep>(\.\s*){2,3}|-|,)\s* (?<close>-?\d+(\.\d+)?)$ /x.freeze LETTER_MATCHER = /^(?<open>\w) \s*(?<sep>(\.\s*){2,3}|-|,)\s* (?<close>\w)$ /x.freeze # An object that converts a String to a Range class StringToRangeConverter < Converter # Convert value to Range type with possible ranges # # @param [Object] value # # @example # converter.call("0,9") # => (0..9) # # @example # converter.call("0-9") # => (0..9) # # @api public def call(value, strict: config.strict) if match = value.match(SINGLE_DIGIT_MATCHER) digit = cast_to_num(match[:digit]) ::Range.new(digit, digit) elsif match = value.match(DIGIT_MATCHER) open = cast_to_num(match[:open]) close = cast_to_num(match[:close]) ::Range.new(open, close, match[:sep].gsub(/\s*/, "") == "...") elsif match = value.match(LETTER_MATCHER) ::Range.new(match[:open], match[:close], match[:sep].gsub(/\s*/, "") == "...") else strict ? raise_conversion_type(value) : value end end # Convert range end to numeric value # # @api private def cast_to_num(str) Integer(str) rescue ArgumentError Float(str) rescue ArgumentError nil end end def self.load(conversions) [ StringToRangeConverter.new(:string, :range), NullConverter.new(:range, :range) ].each do |converter| conversions.register converter end end end # RangeConverters end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/converters/array.rb
lib/necromancer/converters/array.rb
# frozen_string_literal: true require "set" require_relative "../converter" require_relative "boolean" require_relative "numeric" module Necromancer # Container for Array converter classes module ArrayConverters ARRAY_MATCHER = /^(.+?(\s*(?<sep>(,|-))\s*))+/x.freeze # An object that converts a String to an Array class StringToArrayConverter < Converter # Convert string value to array # # @example # converter.call("a, b, c") # => ["a", "b", "c"] # # @example # converter.call("1 - 2 - 3") # => ["1", "2", "3"] # # @api public def call(value, strict: config.strict) return [] if value.to_s.empty? if match = value.to_s.match(ARRAY_MATCHER) value.to_s.split(match[:sep]) else strict ? raise_conversion_type(value) : Array(value) end end end class StringToBooleanArrayConverter < Converter # @example # converter.call("t,f,yes,no") # => [true, false, true, false] # # @param [Array] value # the array value to boolean # # @api public def call(value, strict: config.strict) array_converter = StringToArrayConverter.new(:string, :array) array = array_converter.(value, strict: strict) bool_converter = ArrayToBooleanArrayConverter.new(:array, :boolean) bool_converter.(array, strict: strict) end end class StringToIntegerArrayConverter < Converter # @example # converter.call("1,2,3") # => [1, 2, 3] # # @api public def call(string, strict: config.strict) array_converter = StringToArrayConverter.new(:string, :array) array = array_converter.(string, strict: strict) int_converter = ArrayToIntegerArrayConverter.new(:array, :integers) int_converter.(array, strict: strict) end end class StringToFloatArrayConverter < Converter # @example # converter.call("1,2,3") # => [1.0, 2.0, 3.0] # # @api public def call(string, strict: config.strict) array_converter = StringToArrayConverter.new(:string, :array) array = array_converter.(string, strict: strict) float_converter = ArrayToFloatArrayConverter.new(:array, :floats) float_converter.(array, strict: strict) end end class StringToNumericArrayConverter < Converter # Convert string value to array with numeric values # # @example # converter.call("1,2.0,3") # => [1, 2.0, 3] # # @api public def call(string, strict: config.strict) array_converter = StringToArrayConverter.new(:string, :array) array = array_converter.(string, strict: strict) num_converter = ArrayToNumericArrayConverter.new(:array, :numeric) num_converter.(array, strict: strict) end end class ArrayToIntegerArrayConverter < Converter # @example # converter.call(["1", "2", "3"]) # => [1, 2, 3] # # @api public def call(array, strict: config.strict) int_converter = NumericConverters::StringToIntegerConverter.new(:string, :integer) array.map { |val| int_converter.(val, strict: strict) } end end class ArrayToFloatArrayConverter < Converter # @example # converter.call(["1", "2", "3"]) # => [1.0, 2.0, 3.0] # # @api public def call(array, strict: config.strict) float_converter = NumericConverters::StringToFloatConverter.new(:string, :float) array.map { |val| float_converter.(val, strict: strict) } end end # An object that converts an array to an array with numeric values class ArrayToNumericArrayConverter < Converter # Convert an array to an array of numeric values # # @example # converter.call(["1", "2.3", "3.0]) # => [1, 2.3, 3.0] # # @param [Array] value # the value to convert # # @api public def call(value, strict: config.strict) num_converter = NumericConverters::StringToNumericConverter.new(:string, :numeric) value.map { |val| num_converter.(val, strict: strict) } end end # An object that converts an array to an array with boolean values class ArrayToBooleanArrayConverter < Converter # @example # converter.call(["t", "f", "yes", "no"]) # => [true, false, true, false] # # @param [Array] value # the array value to boolean # # @api public def call(value, strict: config.strict) bool_converter = BooleanConverters::StringToBooleanConverter.new(:string, :boolean) value.map { |val| bool_converter.(val, strict: strict) } end end # An object that converts an object to an array class ObjectToArrayConverter < Converter # Convert an object to an array # # @example # converter.call({x: 1}) # => [[:x, 1]] # # @api public def call(value, strict: config.strict) Array(value) rescue StandardError strict ? raise_conversion_type(value) : value end end # An object that converts an array to a set class ArrayToSetConverter < Converter # Convert an array to a set # # @example # converter.call([:x, :y, :x, 1, 2, 1]) # => <Set: {:x, :y, 1, 2}> # # @param [Array] value # the array to convert # # @api public def call(value, strict: config.strict) value.to_set rescue StandardError strict ? raise_conversion_type(value) : value end end def self.load(conversions) [ NullConverter.new(:array, :array), StringToArrayConverter.new(:string, :array), StringToBooleanArrayConverter.new(:string, :bools), StringToBooleanArrayConverter.new(:string, :booleans), StringToIntegerArrayConverter.new(:string, :integers), StringToIntegerArrayConverter.new(:string, :ints), StringToFloatArrayConverter.new(:string, :floats), StringToNumericArrayConverter.new(:string, :numerics), StringToNumericArrayConverter.new(:string, :nums), ArrayToNumericArrayConverter.new(:array, :numerics), ArrayToNumericArrayConverter.new(:array, :nums), ArrayToIntegerArrayConverter.new(:array, :integers), ArrayToIntegerArrayConverter.new(:array, :ints), ArrayToFloatArrayConverter.new(:array, :floats), ArrayToBooleanArrayConverter.new(:array, :booleans), ArrayToBooleanArrayConverter.new(:array, :bools), ObjectToArrayConverter.new(:object, :array), ObjectToArrayConverter.new(:hash, :array) ].each do |converter| conversions.register converter end end end # ArrayConverters end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/converters/boolean.rb
lib/necromancer/converters/boolean.rb
# frozen_string_literal: true require_relative "../converter" require_relative "../null_converter" module Necromancer # Container for Boolean converter classes module BooleanConverters TRUE_MATCHER = /^(yes|y|on|t(rue)?|1)$/i.freeze FALSE_MATCHER = /^(no|n|off|f(alse)?|0)$/i.freeze # An object that converts a String to a Boolean class StringToBooleanConverter < Converter # Convert value to boolean type including range of strings # # @param [Object] value # # @example # converter.call("True") # => true # # other values converted to true are: # 1, t, T, TRUE, true, True, y, Y, YES, yes, Yes, on, ON # # @example # converter.call("False") # => false # # other values coerced to false are: # 0, f, F, FALSE, false, False, n, N, NO, no, No, off, OFF # # @api public def call(value, strict: config.strict) case value.to_s when TRUE_MATCHER then true when FALSE_MATCHER then false else strict ? raise_conversion_type(value) : value end end end # An object that converts an Integer to a Boolean class IntegerToBooleanConverter < Converter # Convert integer to boolean # # @example # converter.call(1) # => true # # @example # converter.call(0) # => false # # @api public def call(value, strict: config.strict) !value.zero? rescue StandardError strict ? raise_conversion_type(value) : value end end # An object that converts a Boolean to an Integer class BooleanToIntegerConverter < Converter # Convert boolean to integer # # @example # converter.call(true) # => 1 # # @example # converter.call(false) # => 0 # # @api public def call(value, strict: config.strict) if %w[TrueClass FalseClass].include?(value.class.name) value ? 1 : 0 else strict ? raise_conversion_type(value) : value end end end def self.load(conversions) [ StringToBooleanConverter.new(:string, :boolean), IntegerToBooleanConverter.new(:integer, :boolean), BooleanToIntegerConverter.new(:boolean, :integer), NullConverter.new(:boolean, :boolean) ].each do |converter| conversions.register converter end end end # BooleanConverters end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/converters/date_time.rb
lib/necromancer/converters/date_time.rb
# frozen_string_literal: true require "date" require "time" require_relative "../converter" require_relative "../null_converter" module Necromancer # Container for Date converter classes module DateTimeConverters # An object that converts a String to a Date class StringToDateConverter < Converter # Convert a string value to a Date # # @example # converter.call("1-1-2015") # => "2015-01-01" # converter.call("01/01/2015") # => "2015-01-01" # converter.call("2015-11-12") # => "2015-11-12" # converter.call("12/11/2015") # => "2015-11-12" # # @api public def call(value, strict: config.strict) Date.parse(value) rescue StandardError strict ? raise_conversion_type(value) : value end end # An object that converts a String to a DateTime class StringToDateTimeConverter < Converter # Convert a string value to a DateTime # # @example # converer.call("1-1-2015") # => "2015-01-01T00:00:00+00:00" # converer.call("1-1-2015 15:12:44") # => "2015-01-01T15:12:44+00:00" # # @api public def call(value, strict: config.strict) DateTime.parse(value) rescue StandardError strict ? raise_conversion_type(value) : value end end class StringToTimeConverter < Converter # Convert a String value to a Time value # # @param [String] value # the value to convert # # @example # converter.call("01-01-2015") # => 2015-01-01 00:00:00 +0100 # converter.call("01-01-2015 08:35") # => 2015-01-01 08:35:00 +0100 # converter.call("12:35") # => 2015-01-04 12:35:00 +0100 # # @api public def call(value, strict: config.strict) Time.parse(value) rescue StandardError strict ? raise_conversion_type(value) : value end end def self.load(conversions) [ StringToDateConverter.new(:string, :date), NullConverter.new(:date, :date), StringToDateTimeConverter.new(:string, :datetime), NullConverter.new(:datetime, :datetime), StringToTimeConverter.new(:string, :time), NullConverter.new(:time, :time) ].each do |converter| conversions.register converter end end end # DateTimeConverters end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/converters/hash.rb
lib/necromancer/converters/hash.rb
# frozen_string_literal: true require_relative "../converter" require_relative "boolean" require_relative "numeric" module Necromancer module HashConverters # An object that converts a String to a Hash class StringToHashConverter < Converter DEFAULT_CONVERSION = ->(val, *_rest) { val } # Convert string value to hash # # @example # converter.call("a:1 b:2 c:3") # # => {a: "1", b: "2", c: "3"} # # @example # converter.call("a=1 & b=3 & c=3") # # => {a: "1", b: "2", c: "3"} # # @api public def call(value, strict: config.strict, value_converter: DEFAULT_CONVERSION) values = value.split(/\s*[& ]\s*/) values.each_with_object({}) do |pair, pairs| key, value = pair.split(/[=:]/, 2) value_converted = value_converter.(value, strict: strict) if current = pairs[key.to_sym] pairs[key.to_sym] = Array(current) << value_converted else pairs[key.to_sym] = value_converted end pairs end end end class StringToIntegerHashConverter < Converter # Convert string value to hash with integer values # # @example # converter.call("a:1 b:2 c:3") # # => {a: 1, b: 2, c: 3} # # @api public def call(value, strict: config.strict) int_converter = NumericConverters::StringToIntegerConverter.new(:string, :integer) hash_converter = StringToHashConverter.new(:string, :hash) hash_converter.(value, strict: strict, value_converter: int_converter) end end class StringToFloatHashConverter < Converter # Convert string value to hash with float values # # @example # converter.call("a:1 b:2 c:3") # # => {a: 1.0, b: 2.0, c: 3.0} # # @api public def call(value, strict: config.strict) float_converter = NumericConverters::StringToFloatConverter.new(:string, :float) hash_converter = StringToHashConverter.new(:string, :hash) hash_converter.(value, strict: strict, value_converter: float_converter) end end class StringToNumericHashConverter < Converter # Convert string value to hash with numeric values # # @example # converter.call("a:1 b:2.0 c:3") # # => {a: 1, b: 2.0, c: 3} # # @api public def call(value, strict: config.strict) num_converter = NumericConverters::StringToNumericConverter.new(:string, :numeric) hash_converter = StringToHashConverter.new(:string, :hash) hash_converter.(value, strict: strict, value_converter: num_converter) end end class StringToBooleanHashConverter < Converter # Convert string value to hash with boolean values # # @example # converter.call("a:yes b:no c:t") # # => {a: true, b: false, c: true} # # @api public def call(value, strict: config.strict) bool_converter = BooleanConverters::StringToBooleanConverter.new(:string, :boolean) hash_converter = StringToHashConverter.new(:string, :hash) hash_converter.(value, strict: strict, value_converter: bool_converter) end end def self.load(conversions) [ NullConverter.new(:hash, :hash), StringToHashConverter.new(:string, :hash), StringToIntegerHashConverter.new(:string, :int_hash), StringToIntegerHashConverter.new(:string, :integer_hash), StringToFloatHashConverter.new(:string, :float_hash), StringToNumericHashConverter.new(:string, :num_hash), StringToNumericHashConverter.new(:string, :numeric_hash), StringToBooleanHashConverter.new(:string, :boolean_hash), StringToBooleanHashConverter.new(:string, :bool_hash) ].each do |converter| conversions.register(converter) end end end # HashConverters end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
piotrmurach/necromancer
https://github.com/piotrmurach/necromancer/blob/fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5/lib/necromancer/converters/numeric.rb
lib/necromancer/converters/numeric.rb
# frozen_string_literal: true require_relative "../converter" require_relative "../null_converter" module Necromancer # Container for Numeric converter classes module NumericConverters INTEGER_MATCHER = /^\s*[-+]?\s*(\d[\d\s]*)?$/.freeze FLOAT_MATCHER = /^\s*[-+]?([\d\s]*)(\.[\d\s]+)?([eE]?[-+]?[\d\s]+)?$/.freeze # An object that converts a String to an Integer class StringToIntegerConverter < Converter # Convert string value to integer # # @example # converter.call("1abc") # => 1 # # @api public def call(value, strict: config.strict) Integer(value) rescue StandardError strict ? raise_conversion_type(value) : value.to_i end end # An object that converts an Integer to a String class IntegerToStringConverter < Converter # Convert integer value to string # # @example # converter.call(1) # => "1" # # @api public def call(value, **_) value.to_s end end # An object that converts a String to a Float class StringToFloatConverter < Converter # Convert string to float value # # @example # converter.call("1.2") # => 1.2 # # @api public def call(value, strict: config.strict) Float(value) rescue StandardError strict ? raise_conversion_type(value) : value.to_f end end # An object that converts a String to a Numeric class StringToNumericConverter < Converter # Convert string to numeric value # # @example # converter.call("1.0") # => 1.0 # # @example # converter.call("1") # => 1 # # @api public def call(value, strict: config.strict) case value when INTEGER_MATCHER StringToIntegerConverter.new(:string, :integer).(value, strict: strict) when FLOAT_MATCHER StringToFloatConverter.new(:string, :float).(value, strict: strict) else strict ? raise_conversion_type(value) : value end end end def self.load(conversions) [ StringToIntegerConverter.new(:string, :integer), IntegerToStringConverter.new(:integer, :string), NullConverter.new(:integer, :integer), StringToFloatConverter.new(:string, :float), NullConverter.new(:float, :float), StringToNumericConverter.new(:string, :numeric) ].each do |converter| conversions.register converter end end end # Conversion end # Necromancer
ruby
MIT
fc815d9ca6f8e5820e4b22aa1ea0e0ad7e3f9cf5
2026-01-04T17:47:00.524454Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/init.rb
init.rb
require 'seer'
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/pie_chart_spec.rb
spec/pie_chart_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer::PieChart" do before :each do @chart = Seer::PieChart.new( :data => [0,1,2,3], :label_method => 'to_s', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' ) end describe 'defaults' do it_should_behave_like 'it sets default values' end describe 'graph options' do [:background_color, :border_color, :enable_tooltip, :focus_border_color, :height, :is_3_d, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :pie_join_angle, :pie_minimal_angle, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :tooltip_width, :width].each do |accessor| it "sets its #{accessor} value" do @chart.send("#{accessor}=", 'foo') @chart.send(accessor).should == 'foo' end end it_should_behave_like 'it has colors attribute' end it 'renders as JavaScript' do (@chart.to_js =~ /javascript/).should be_true (@chart.to_js =~ /piechart/).should be_true end it 'sets its data columns' do @chart.data_columns.should =~ /addRows\(4\)/ end it 'sets its data table' do @chart.data_table.to_s.should set_value(0, 0,'0') @chart.data_table.to_s.should set_value(0, 1, 8) @chart.data_table.to_s.should set_value(1, 0,'1') @chart.data_table.to_s.should set_value(1, 1, 8) @chart.data_table.to_s.should set_value(2, 0,'2') @chart.data_table.to_s.should set_value(2, 1, 8) @chart.data_table.to_s.should set_value(3, 0,'3') @chart.data_table.to_s.should set_value(3, 1, 8) end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/seer_spec.rb
spec/seer_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer" do require 'rubygems' it 'validates hexadecimal numbers' do invalid = [nil, '', 'food', 'bdadce', 123456] valid = ['#000000','#ffffff'] invalid.each{ |e| Seer.valid_hex_number?(e).should be_false } valid.each { |e| Seer.valid_hex_number?(e).should be_true } end describe 'visualize' do it 'raises an error for invalid visualizaters' do invalid = [:random, 'something'] invalid.each do |e| lambda do Seer.visualize([1,2,3], :as => e) end.should raise_error(ArgumentError) end end it 'raises an error for missing data' do _data = [] lambda do Seer.visualize(_data, :as => :bar_chart) end.should raise_error(ArgumentError) end it 'accepts valid visualizers' do Seer::VISUALIZERS.each do |v| lambda do Seer::visualize( [0,1,2,3], :as => v, :in_element => 'chart', :series => {:label => 'to_s', :data => 'size'}, :chart_options => {} ) end.should_not raise_error(ArgumentError) end end end describe 'private chart methods' do it 'renders an area chart' do (Seer.send(:area_chart, [0,1,2,3], :as => :area_chart, :in_element => 'chart', :series => { :series_label => 'to_s', :data_label => 'to_s', :data_method => 'size', :data_series => [[1,2,3],[3,4,5]] }, :chart_options => {} ) =~ /areachart/).should be_true end it 'renders a bar chart' do (Seer.send(:bar_chart, [0,1,2,3], :as => :bar_chart, :in_element => 'chart', :series => { :series_label => 'to_s', :data_method => 'size' }, :chart_options => {} ) =~ /barchart/).should be_true end it 'renders a column chart' do (Seer.send(:column_chart, [0,1,2,3], :as => :column_chart, :in_element => 'chart', :series => { :series_label => 'to_s', :data_method => 'size' }, :chart_options => {} ) =~ /columnchart/).should be_true end it 'renders a gauge' do (Seer.send(:gauge, [0,1,2,3], :as => :gauge, :in_element => 'chart', :series => { :series_label => 'to_s', :data_method => 'size' }, :chart_options => {} ) =~ /gauge/).should be_true end it 'renders a line chart' do (Seer.send(:line_chart, [0,1,2,3], :as => :line_chart, :in_element => 'chart', :series => { :series_label => 'to_s', :data_label => 'to_s', :data_method => 'size', :data_series => [[1,2,3],[3,4,5]] }, :chart_options => {} ) =~ /linechart/).inspect #should be_true end it 'renders a pie chart' do (Seer.send(:pie_chart, [0,1,2,3], :as => :pie_chart, :in_element => 'chart', :series => { :series_label => 'to_s', :data_method => 'size' }, :chart_options => {} ) =~ /piechart/).should be_true end end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/column_chart_spec.rb
spec/column_chart_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer::ColumnChart" do before :each do @chart = Seer::ColumnChart.new( :data => [0,1,2,3], :label_method => 'to_s', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' ) end describe 'defaults' do it_should_behave_like 'it sets default values' end describe 'graph options' do [:axis_color, :axis_background_color, :axis_font_size, :background_color, :border_color, :enable_tooltip, :focus_border_color, :height, :is_3_d, :is_stacked, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :log_scale, :max, :min, :reverse_axis, :show_categories, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :tooltip_width, :width].each do |accessor| it "sets its #{accessor} value" do @chart.send("#{accessor}=", 'foo') @chart.send(accessor).should == 'foo' end end it_should_behave_like 'it has colors attribute' end it 'renders as JavaScript' do (@chart.to_js =~ /javascript/).should be_true (@chart.to_js =~ /columnchart/).should be_true end it 'sets its data columns' do @chart.data_columns.should =~ /addRows\(4\)/ end it 'sets its data table' do @chart.data_table.to_s.should set_value(0, 0,'0') @chart.data_table.to_s.should set_value(0, 1, 8) @chart.data_table.to_s.should set_value(1, 0,'1') @chart.data_table.to_s.should set_value(1, 1, 8) @chart.data_table.to_s.should set_value(2, 0,'2') @chart.data_table.to_s.should set_value(2, 1, 8) @chart.data_table.to_s.should set_value(3, 0,'3') @chart.data_table.to_s.should set_value(3, 1, 8) end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/helpers.rb
spec/helpers.rb
describe "it has colors attribute", :shared => true do it 'sets its colors value' do color_list = ['#7e7587','#990000','#009900', '#3e5643', '#660000', '#003300'] @chart.colors = color_list @chart.colors.should == color_list end it 'colors should be an array' do lambda { @chart.colors = '#000000' }.should raise_error(ArgumentError) end it 'colors should be valid hex values' do lambda { @chart.colors = ['#000000', 'NOTHEX'] }.should raise_error(ArgumentError) end end describe "it sets default values", :shared => true do it 'colors' do @chart.colors.should == Seer::Chart::DEFAULT_COLORS end it 'legend' do @chart.legend.should == Seer::Chart::DEFAULT_LEGEND_LOCATION end it 'height' do @chart.height.should == Seer::Chart::DEFAULT_HEIGHT end it 'width' do @chart.width.should == Seer::Chart::DEFAULT_WIDTH end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/chart_spec.rb
spec/chart_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer::Chart" do before :all do @chart = Seer::AreaChart.new( :data => [0,1,2,3], :series_label => 'to_s', :data_series => [[1,2,3],[3,4,5]], :data_label => 'to_s', :data_method => 'size', :chart_options => { :legend => 'right', :title_x => 'Something' }, :chart_element => 'chart' ) end it 'sets the chart element' do @chart.in_element = 'foo' @chart.chart_element.should == 'foo' end describe 'sets colors' do it 'accepting valid values' do @chart.colors = ["#ff0000", "#00ff00"] @chart.colors.should == ["#ff0000", "#00ff00"] end it 'raising an error on invalid values' do lambda do @chart.colors = 'fred' end.should raise_error(ArgumentError) lambda do @chart.colors = [0,1,2] end.should raise_error(ArgumentError) end end it 'formats colors' do @chart.colors = ["#ff0000"] @chart.formatted_colors.should == "['ff0000']" end it 'sets its data columns' do @chart.data_columns.should =~ /addRows\(5\)/ @chart.data_columns.should =~ /addColumn\('string', 'Date'\)/ @chart.data_columns.should =~ /addColumn\('number', '0'\)/ @chart.data_columns.should =~ /addColumn\('number', '1'\)/ @chart.data_columns.should =~ /addColumn\('number', '2'\)/ @chart.data_columns.should =~ /addColumn\('number', '3'\)/ end it 'sets its options' do @chart.options.should =~ /options\['titleX'\] = 'Something'/ end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/gauge_spec.rb
spec/gauge_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer::Gauge" do before :each do @chart = Seer::Gauge.new( :data => [0,1,2,3], :label_method => 'to_s', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' ) end describe 'defaults' do it 'height' do @chart.height.should == Seer::Chart::DEFAULT_HEIGHT end it 'width' do @chart.width.should == Seer::Chart::DEFAULT_WIDTH end end describe 'graph options' do [:green_from, :green_to, :height, :major_ticks, :max, :min, :minor_ticks, :red_from, :red_to, :width, :yellow_from, :yellow_to].each do |accessor| it "sets its #{accessor} value" do @chart.send("#{accessor}=", 'foo') @chart.send(accessor).should == 'foo' end end it_should_behave_like 'it has colors attribute' end it 'renders as JavaScript' do (@chart.to_js =~ /javascript/).should be_true (@chart.to_js =~ /gauge/).should be_true end it 'sets its data columns' do @chart.data_columns.should =~ /addRows\(4\)/ end it 'sets its data table' do @chart.data_table.to_s.should set_value(0, 0,'0') @chart.data_table.to_s.should set_value(0, 1, 8) @chart.data_table.to_s.should set_value(1, 0,'1') @chart.data_table.to_s.should set_value(1, 1, 8) @chart.data_table.to_s.should set_value(2, 0,'2') @chart.data_table.to_s.should set_value(2, 1, 8) @chart.data_table.to_s.should set_value(3, 0,'3') @chart.data_table.to_s.should set_value(3, 1, 8) end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/bar_chart_spec.rb
spec/bar_chart_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer::BarChart" do before :each do @chart = Seer::BarChart.new( :data => [0,1,2,3], :label_method => 'to_s', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' ) end describe 'defaults' do it_should_behave_like 'it sets default values' end describe 'graph options' do [:axis_color, :axis_background_color, :axis_font_size, :background_color, :border_color, :enable_tooltip, :focus_border_color, :height, :is_3_d, :is_stacked, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :log_scale, :max, :min, :reverse_axis, :show_categories, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :tooltip_width, :width].each do |accessor| it "sets its #{accessor} value" do @chart.send("#{accessor}=", 'foo') @chart.send(accessor).should == 'foo' end end it_should_behave_like 'it has colors attribute' end it 'renders as JavaScript' do (@chart.to_js =~ /javascript/).should be_true (@chart.to_js =~ /barchart/).should be_true end it 'sets its data columns' do @chart.data_columns.should =~ /addRows\(4\)/ end it 'sets its data table' do @chart.data_table.to_s.should set_value(0, 0,'0') @chart.data_table.to_s.should set_value(0, 1, 8) @chart.data_table.to_s.should set_value(1, 0,'1') @chart.data_table.to_s.should set_value(1, 1, 8) @chart.data_table.to_s.should set_value(2, 0,'2') @chart.data_table.to_s.should set_value(2, 1, 8) @chart.data_table.to_s.should set_value(3, 0,'3') @chart.data_table.to_s.should set_value(3, 1, 8) end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/area_chart_spec.rb
spec/area_chart_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer::AreaChart" do before :each do @chart = Seer::AreaChart.new( :data => [0,1,2,3], :series_label => 'to_s', :data_series => [[1,2,3],[3,4,5]], :data_label => 'to_s', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' ) end describe 'defaults' do it_should_behave_like 'it sets default values' end describe 'graph options' do [:axis_color, :axis_background_color, :axis_font_size, :background_color, :border_color, :enable_tooltip, :focus_border_color, :height, :is_stacked, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :line_size, :log_scale, :max, :min, :point_size, :reverse_axis, :show_categories, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :number, :tooltip_width, :width].each do |accessor| it "sets its #{accessor} value" do @chart.send("#{accessor}=", 'foo') @chart.send(accessor).should == 'foo' end end it_should_behave_like 'it has colors attribute' end it 'renders as JavaScript' do (@chart.to_js =~ /javascript/).should be_true (@chart.to_js =~ /areachart/).should be_true end it 'sets its data columns' do @chart.data_columns.should =~ /addRows\(5\)/ @chart.data_columns.should add_column('string', 'Date') @chart.data_columns.should add_column('number', '0') @chart.data_columns.should add_column('number', '1') @chart.data_columns.should add_column('number', '2') @chart.data_columns.should add_column('number', '3') end it 'sets its data table' do @chart.data_table.to_s.should set_cell(0, 0,'1') @chart.data_table.to_s.should set_cell(1, 0,'2') @chart.data_table.to_s.should set_cell(2, 0,'3') @chart.data_table.to_s.should set_cell(3, 0,'4') @chart.data_table.to_s.should set_cell(4, 0,'5') @chart.data_table.to_s.should set_cell(0,1,8) @chart.data_table.to_s.should set_cell(2,1,8) @chart.data_table.to_s.should set_cell(0,2,8) @chart.data_table.to_s.should set_cell(1,2,8) @chart.data_table.to_s.should set_cell(2,2,8) end describe 'when data_series is an array of arrays of arrays/hashes' do before(:each) do data_series = Array.new(3) {|i| [[i, i+1], [i+1, i+2]]} @chart = Seer::AreaChart.new( :data => [0,1,2,3], :series_label => 'to_s', :data_series => data_series, :data_label => 'first', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' ) end it 'calculates number of rows' do @chart.data_columns.should =~ /addRows\(4\)/ end it 'sets its data table' do @chart.data_table.to_s.should set_cell(0, 0,'0') @chart.data_table.to_s.should set_cell(1, 0,'1') @chart.data_table.to_s.should set_cell(2, 0,'2') @chart.data_table.to_s.should set_cell(3, 0,'3') end end describe 'should receive options' do before(:each) do data_series = Array.new(3) {|i| [[i, i+1], [i+1, i+2]]} @options = { :data => [0,1,2,3], :series_label => 'to_s', :data_series => data_series, :data_label => 'first', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' } end it 'should receive :is_stacked option' do create_chart_with_option(:is_stacked => true).to_js.should =~ /options\['isStacked'\] = true/ end end end def create_chart_with_option(option) Seer::AreaChart.new(@options.merge(option)) end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/line_chart_spec.rb
spec/line_chart_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer::LineChart" do before :each do @chart = Seer::LineChart.new( :data => [0,1,2,3], :series_label => 'to_s', :data_series => [[1,2,3],[3,4,5]], :data_label => 'to_s', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' ) end describe 'defaults' do it_should_behave_like 'it sets default values' end describe 'graph options' do [:axis_color, :axis_background_color, :axis_font_size, :background_color, :border_color, :enable_tooltip, :focus_border_color, :height, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :line_size, :log_scale, :max, :min, :point_size, :reverse_axis, :show_categories, :smooth_line, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :number, :tooltip_width, :width].each do |accessor| it "sets its #{accessor} value" do @chart.send("#{accessor}=", 'foo') @chart.send(accessor).should == 'foo' end end it_should_behave_like 'it has colors attribute' end it 'renders as JavaScript' do (@chart.to_js =~ /javascript/).should be_true (@chart.to_js =~ /linechart/).should be_true end it 'sets its data columns' do @chart.data_columns.should =~ /addRows\(5\)/ @chart.data_columns.should add_column('string', 'Date') @chart.data_columns.should add_column('number', '0') @chart.data_columns.should add_column('number', '1') @chart.data_columns.should add_column('number', '2') @chart.data_columns.should add_column('number', '3') end it 'sets its data table' do @chart.data_table.to_s.should set_cell(0, 0,'1') @chart.data_table.to_s.should set_cell(1, 0,'2') @chart.data_table.to_s.should set_cell(2, 0,'3') @chart.data_table.to_s.should set_cell(3, 0,'4') @chart.data_table.to_s.should set_cell(4, 0,'5') @chart.data_table.to_s.should set_cell(0,1,8) @chart.data_table.to_s.should set_cell(2,1,8) @chart.data_table.to_s.should set_cell(0,2,8) @chart.data_table.to_s.should set_cell(1,2,8) @chart.data_table.to_s.should set_cell(2,2,8) end describe 'when data_series is an array of arrays of arrays/hashes' do before(:each) do data_series = Array.new(3) {|i| [[i, i+1], [i+1, i+2]]} @chart = Seer::LineChart.new( :data => [0,1,2,3], :series_label => 'to_s', :data_series => data_series, :data_label => 'first', :data_method => 'size', :chart_options => {}, :chart_element => 'chart' ) end it 'calculates number of rows' do @chart.data_columns.should =~ /addRows\(4\)/ end it 'sets its data table' do @chart.data_table.to_s.should set_cell(0, 0,'0') @chart.data_table.to_s.should set_cell(1, 0,'1') @chart.data_table.to_s.should set_cell(2, 0,'2') @chart.data_table.to_s.should set_cell(3, 0,'3') end end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/custom_matchers.rb
spec/custom_matchers.rb
module CustomMatcher def set_cell(row, column, value) value = "'#{value}'" if value.is_a?(String) simple_matcher("setCell(#{row}, #{column}, #{value})") do |actual| actual =~ /data\.setCell\(#{row},\s*#{column},\s*#{value}\)/ end end def set_value(row, column, value) value = "'#{value}'" if value.is_a?(String) simple_matcher("setValue(#{row}, #{column}, #{value})") do |actual| actual =~ /data\.setValue\(#{row},\s*#{column},\s*#{value}\)/ end end def add_column(column_type, value) simple_matcher("addColumn('#{column_type}', '#{value}')") do |actual| actual =~ /data\.addColumn\('#{column_type}',\s*'#{value}'\)/ end end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/geomap_spec.rb
spec/geomap_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Seer::Geomap" do before :each do class GeoThing def initialize; end def name; 'foo'; end def latitude; -90; end def longitude; -90; end def count; 8; end def geocoded?; true; end end @chart = Seer::Geomap.new( :data => [GeoThing.new, GeoThing.new, GeoThing.new], :label_method => 'name', :data_method => 'count', :chart_options => {}, :chart_element => 'geochart' ) end describe 'defaults' do it 'height' do @chart.height.should == Seer::Chart::DEFAULT_HEIGHT end it 'width' do @chart.width.should == Seer::Chart::DEFAULT_WIDTH end end describe 'graph options' do [:show_zoom_out, :zoom_out_label].each do |accessor| it "sets its #{accessor} value" do @chart.send("#{accessor}=", 'foo') @chart.send(accessor).should == 'foo' end end it_should_behave_like 'it has colors attribute' end it 'renders as JavaScript' do (@chart.to_js =~ /javascript/).should be_true (@chart.to_js =~ /geomap/).should be_true end it 'sets its data columns' do @chart.data_columns.should =~ /addRows\(3\)/ end it 'sets its data table' do @chart.data_table.to_s.should set_value(0, 0,'foo') @chart.data_table.to_s.should set_value(0, 1, 8) @chart.data_table.to_s.should set_value(1, 0,'foo') @chart.data_table.to_s.should set_value(1, 1, 8) @chart.data_table.to_s.should set_value(2, 0,'foo') @chart.data_table.to_s.should set_value(2, 1, 8) end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'rubygems' require 'action_pack' require 'active_support' require 'spec' require 'spec/autorun' require 'seer' require File.dirname(__FILE__) + "/custom_matchers" require File.dirname(__FILE__) + '/helpers' Spec::Runner.configure do |config| config.include(CustomMatcher) end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer.rb
lib/seer.rb
module Seer require 'seer/chart' require 'seer/area_chart' require 'seer/bar_chart' require 'seer/column_chart' require 'seer/gauge' require 'seer/geomap' require 'seer/line_chart' require 'seer/pie_chart' VISUALIZERS = [:area_chart, :bar_chart, :column_chart, :gauge, :geomap, :line_chart, :pie_chart] def self.valid_hex_number?(val) #:nodoc: return false unless val.is_a?(String) && ! val.empty? ! (val =~ /^\#([0-9]|[a-f]|[A-F])+$/).nil? && val.length == 7 end def self.log(message) #:nodoc: RAILS_DEFAULT_LOGGER.info(message) end def self.init_visualization %{ <script type="text/javascript"> var jsapi = (("https:" == document.location.protocol) ? "https://" : "http://"); document.write(unescape("%3Cscript src='" + jsapi + "www.google.com/jsapi' type='text/javascript'%3E%3C/script%3E")); </script> } end def self.visualize(data, args={}) raise ArgumentError, "Seer: Invalid visualizer: #{args[:as]}" unless args[:as] && VISUALIZERS.include?(args[:as]) raise ArgumentError, "Seer: No data provided!" unless data && ! data.empty? self.send(args[:as], data, args) end private def self.area_chart(data, args) AreaChart.render(data, args) end def self.bar_chart(data, args) BarChart.render(data, args) end def self.column_chart(data, args) ColumnChart.render(data, args) end def self.gauge(data, args) Gauge.render(data, args) end def self.geomap(data, args) Geomap.render(data, args) end def self.line_chart(data, args) LineChart.render(data, args) end def self.pie_chart(data, args) PieChart.render(data, args) end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer/bar_chart.rb
lib/seer/bar_chart.rb
module Seer # =USAGE # # In your controller: # # @data = Widgets.all # Must be an array, and must respond # # to the data method specified below (in this example, 'quantity') # # In your view: # # <div id="chart"></div> # # <%= Seer::visualize( # @widgets, # :as => :bar_chart, # :in_element => 'chart', # :series => {:series_label => 'name', :data_method => 'quantity'}, # :chart_options => { # :height => 300, # :width => 200 * @widgets.size, # :is_3_d => false, # :legend => 'none', # :colors => ["#990000"], # :title => "Widget Quantities", # :title_x => 'Quantity', # :title_y => 'Widgets' # } # ) # -%> # # Colors are treated differently for 2d and 3d graphs. If you set is_3_d to true, set the # graph colors like this: # # :colors => "[{color:'#990000', darker:'#660000'}]", # # For details on the chart options, see the Google API docs at # http://code.google.com/apis/visualization/documentation/gallery/barchart.html # class BarChart include Seer::Chart # Chart options accessors attr_accessor :axis_color, :axis_background_color, :axis_font_size, :background_color, :border_color, :data_table, :enable_tooltip, :focus_border_color, :font_size, :height, :is_3_d, :is_stacked, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :log_scale, :max, :min, :reverse_axis, :show_categories, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :tooltip_width, :width # Graph data attr_accessor :data, :data_method, :label_method def initialize(args={}) #:nodoc: # Standard options args.each{ |method,arg| self.send("#{method}=",arg) if self.respond_to?(method) } # Chart options args[:chart_options].each{ |method, arg| self.send("#{method}=",arg) if self.respond_to?(method) } # Handle defaults @colors ||= args[:chart_options][:colors] || DEFAULT_COLORS @legend ||= args[:chart_options][:legend] || DEFAULT_LEGEND_LOCATION @height ||= args[:chart_options][:height] || DEFAULT_HEIGHT @width ||= args[:chart_options][:width] || DEFAULT_WIDTH @is_3_d ||= args[:chart_options][:is_3_d] @data_table = [] end def data_table #:nodoc: data.each_with_index do |datum, column| @data_table << [ " data.setValue(#{column}, 0,'#{datum.send(label_method)}');\r", " data.setValue(#{column}, 1, #{datum.send(data_method)});\r" ] end @data_table end def is_3_d #:nodoc: @is_3_d.blank? ? false : @is_3_d end def nonstring_options #:nodoc: [:axis_font_size, :colors, :enable_tooltip, :is_3_d, :is_stacked, :legend_font_size, :log_scale, :max, :min, :reverse_axis, :show_categories, :title_font_size, :tooltip_font_size, :tooltip_width] end def string_options #:nodoc: [:axis_color, :axis_background_color, :background_color, :border_color, :focus_border_color, :height, :legend, :legend_background_color, :legend_text_color, :title, :title_x, :title_y, :title_color, :width] end def to_js #:nodoc: %{ <script type="text/javascript"> google.load('visualization', '1', {'packages':['barchart']}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); #{data_columns} #{data_table.join("\r")} var options = {}; #{options} var container = document.getElementById('#{self.chart_element}'); var chart = new google.visualization.BarChart(container); chart.draw(data, options); } </script> } end def self.render(data, args) #:nodoc: graph = Seer::BarChart.new( :label_method => args[:series][:series_label], :data_method => args[:series][:data_method], :chart_options => args[:chart_options], :chart_element => args[:in_element] || 'chart', :data => data ) graph.to_js end end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer/chart.rb
lib/seer/chart.rb
module Seer module Chart #:nodoc: attr_accessor :chart_element, :colors DEFAULT_COLORS = ['#324F69','#919E4B', '#A34D4D', '#BEC8BE'] DEFAULT_LEGEND_LOCATION = 'bottom' DEFAULT_HEIGHT = 350 DEFAULT_WIDTH = 550 def in_element=(elem) @chart_element = elem end def colors=(colors_list) unless colors_list.include?('darker') raise ArgumentError, "Invalid color option: #{colors_list}" unless colors_list.is_a?(Array) colors_list.each do |color| raise ArgumentError, "Invalid color option: #{colors_list}" unless Seer.valid_hex_number?(color) end end @colors = colors_list end def formatted_colors if @colors.include?('darker') @colors else "[#{@colors.map{|color| "'#{color.gsub(/\#/,'')}'"} * ','}]" end end def data_columns _data_columns = " data.addRows(#{data_table.size});\r" _data_columns << " data.addColumn('string', '#{label_method}');\r" _data_columns << " data.addColumn('number', '#{data_method}');\r" _data_columns end def options _options = "" nonstring_options.each do |opt| next unless self.send(opt) if opt == :colors _options << " options['#{opt.to_s.camelize(:lower)}'] = #{self.send(:formatted_colors)};\r" else _options << " options['#{opt.to_s.camelize(:lower)}'] = #{self.send(opt)};\r" end end string_options.each do |opt| next unless self.send(opt) _options << " options['#{opt.to_s.camelize(:lower)}'] = '#{self.send(opt)}';\r" end _options end end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer/column_chart.rb
lib/seer/column_chart.rb
module Seer # =USAGE # # In your controller: # # @data = Widgets.all # Must be an array, and must respond # # to the data method specified below (in this example, 'quantity') # # In your view: # # <div id="chart"></div> # # <%= Seer::visualize( # @widgets, # :as => :column_chart, # :in_element => 'chart', # :series => {:series_label => 'name', :data_method => 'quantity'}, # :chart_options => { # :height => 300, # :width => 300, # :is_3_d => true, # :legend => 'none', # :colors => "[{color:'#990000', darker:'#660000'}]", # :title => "Widget Quantities", # :title_x => 'Widgets', # :title_y => 'Quantities' # } # ) # -%> # # Colors are treated differently for 2d and 3d graphs. If you set is_3_d to false, set the # graph color like this: # # :colors => "#990000" # # For details on the chart options, see the Google API docs at # http://code.google.com/apis/visualization/documentation/gallery/columnchart.html # class ColumnChart include Seer::Chart # Chart options accessors attr_accessor :axis_color, :axis_background_color, :axis_font_size, :background_color, :border_color, :enable_tooltip, :focus_border_color, :height, :is_3_d, :is_stacked, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :log_scale, :max, :min, :reverse_axis, :show_categories, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :tooltip_width, :width # Graph data attr_accessor :data, :data_method, :data_table, :label_method def initialize(args={}) #:nodoc: # Standard options args.each{ |method,arg| self.send("#{method}=",arg) if self.respond_to?(method) } # Chart options args[:chart_options].each{ |method, arg| self.send("#{method}=",arg) if self.respond_to?(method) } # Handle defaults @colors ||= args[:chart_options][:colors] || DEFAULT_COLORS @legend ||= args[:chart_options][:legend] || DEFAULT_LEGEND_LOCATION @height ||= args[:chart_options][:height] || DEFAULT_HEIGHT @width ||= args[:chart_options][:width] || DEFAULT_WIDTH @is_3_d ||= args[:chart_options][:is_3_d] @data_table = [] end def data_table #:nodoc: data.each_with_index do |datum, column| @data_table << [ " data.setValue(#{column}, 0,'#{datum.send(label_method)}');\r", " data.setValue(#{column}, 1, #{datum.send(data_method)});\r" ] end @data_table end def is_3_d #:nodoc: @is_3_d.blank? ? false : @is_3_d end def nonstring_options #:nodoc: [:axis_font_size, :colors, :enable_tooltip, :height, :is_3_d, :is_stacked, :legend_font_size, :log_scale, :max, :min, :reverse_axis, :show_categories, :title_font_size, :tooltip_font_size, :tooltip_width, :width] end def string_options #:nodoc: [:axis_color, :axis_background_color, :background_color, :border_color, :focus_border_color, :legend, :legend_background_color, :legend_text_color, :title, :title_x, :title_y, :title_color] end def to_js #:nodoc: %{ <script type="text/javascript"> google.load('visualization', '1', {'packages':['columnchart']}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); #{data_columns} #{data_table.join("\r")} var options = {}; #{options} var container = document.getElementById('#{self.chart_element}'); var chart = new google.visualization.ColumnChart(container); chart.draw(data, options); } </script> } end def self.render(data, args) #:nodoc: graph = Seer::ColumnChart.new( :data => data, :label_method => args[:series][:series_label], :data_method => args[:series][:data_method], :chart_options => args[:chart_options], :chart_element => args[:in_element] || 'chart' ) graph.to_js end end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer/gauge.rb
lib/seer/gauge.rb
module Seer # =USAGE # # In your controller: # # @data = Widgets.all # Must be an array, and must respond # # to the data method specified below (in this example, 'quantity') # # In your view: # # <div id="chart"></div> # # <%= Seer::visualize( # @data, # :as => :gauge, # :in_element => 'chart', # :series => {:series_label => 'name', :data_method => 'quantity'}, # :chart_options => { # :green_from => 0, # :green_to => 50, # :height => 300, # :max => 100, # :min => 0, # :minor_ticks => 5, # :red_from => 76, # :red_to => 100, # :width => 600, # :yellow_from => 51, # :yellow_to => 75 # } # ) # -%> # # For details on the chart options, see the Google API docs at # http://code.google.com/apis/visualization/documentation/gallery/gauge.html # class Gauge include Seer::Chart # Chart options accessors attr_accessor :green_from, :green_to, :height, :major_ticks, :max, :min, :minor_ticks, :red_from, :red_to, :width, :yellow_from, :yellow_to # Graph data attr_accessor :data, :data_method, :data_table, :label_method def initialize(args={}) #:nodoc: # Standard options args.each{ |method,arg| self.send("#{method}=",arg) if self.respond_to?(method) } # Chart options args[:chart_options].each{ |method, arg| self.send("#{method}=",arg) if self.respond_to?(method) } # Handle defaults @height ||= args[:chart_options][:height] || DEFAULT_HEIGHT @width ||= args[:chart_options][:width] || DEFAULT_WIDTH @data_table = [] end def data_table #:nodoc: data.each_with_index do |datum, column| @data_table << [ " data.setValue(#{column}, 0,'#{datum.send(label_method)}');\r", " data.setValue(#{column}, 1, #{datum.send(data_method)});\r" ] end @data_table end def is_3_d #:nodoc: @is_3_d.blank? ? false : @is_3_d end def nonstring_options #:nodoc: [:green_from, :green_to, :height, :major_ticks, :max, :min, :minor_ticks, :red_from, :red_to, :width, :yellow_from, :yellow_to] end def string_options #:nodoc: [] end def to_js #:nodoc: %{ <script type="text/javascript"> google.load('visualization', '1', {'packages':['gauge']}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); #{data_columns} #{data_table.join} var options = {}; #{options} var container = document.getElementById('#{self.chart_element}'); var chart = new google.visualization.Gauge(container); chart.draw(data, options); } </script> } end def self.render(data, args) #:nodoc: graph = Seer::Gauge.new( :data => data, :label_method => args[:series][:series_label], :data_method => args[:series][:data_method], :chart_options => args[:chart_options], :chart_element => args[:in_element] || 'chart' ) graph.to_js end end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false
CoralineAda/seer
https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer/line_chart.rb
lib/seer/line_chart.rb
module Seer # =USAGE # # In your controller: # # @data = Widgets.all # Must be an array of objects that respond to the specidied data method # # (In this example, 'quantity' # # @series = @data.map{|w| w.widget_stats} # An array of arrays # # In your view: # # <div id="chart"></div> # # <%= Seer::visualize( # @data, # :as => :line_chart, # :in_element => 'chart', # :series => { # :series_label => 'name', # :data_label => 'date', # :data_method => 'quantity', # :data_series => @series # }, # :chart_options => { # :height => 300, # :width => 300, # :axis_font_size => 11, # :colors => ['#7e7587','#990000','#009900'], # :title => "Widget Quantities", # :point_size => 5 # } # ) # -%> # # For details on the chart options, see the Google API docs at # http://code.google.com/apis/visualization/documentation/gallery/linechart.html # class LineChart include Seer::Chart # Graph options attr_accessor :axis_color, :axis_background_color, :axis_font_size, :background_color, :border_color, :enable_tooltip, :focus_border_color, :height, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :line_size, :log_scale, :max, :min, :point_size, :reverse_axis, :show_categories, :smooth_line, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :number, :tooltip_width, :width # Graph data attr_accessor :data, :data_label, :data_method, :data_series, :data_table, :series_label def initialize(args={}) #:nodoc: # Standard options args.each{ |method,arg| self.send("#{method}=",arg) if self.respond_to?(method) } # Chart options args[:chart_options].each{ |method, arg| self.send("#{method}=",arg) if self.respond_to?(method) } # Handle defaults @colors ||= args[:chart_options][:colors] || DEFAULT_COLORS @legend ||= args[:chart_options][:legend] || DEFAULT_LEGEND_LOCATION @height ||= args[:chart_options][:height] || DEFAULT_HEIGHT @width ||= args[:chart_options][:width] || DEFAULT_WIDTH @data_table = [] end def data_columns #:nodoc: _data_columns = " data.addRows(#{data_rows.size});\r" _data_columns << " data.addColumn('string', 'Date');\r" if data.first.respond_to?(series_label) data.each{ |datum| _data_columns << " data.addColumn('number', '#{datum.send(series_label)}');\r" } else data.each{ |datum| _data_columns << " data.addColumn('number', '#{series_label}');\r" } end _data_columns end def data_table #:nodoc: _rows = data_rows _rows.each_with_index do |r,i| @data_table << " data.setCell(#{i}, 0,'#{r}');\r" end data_series.each_with_index do |column,i| column.each_with_index do |c,j| @data_table << "data.setCell(#{j},#{i+1},#{c.send(data_method)});\r" end end @data_table end def data_rows data_series.inject([]) do |rows, element| rows |= element.map { |e| e.send(data_label) } end end def nonstring_options #:nodoc: [ :axis_font_size, :colors, :enable_tooltip, :height, :legend_font_size, :line_size, :log_scale, :max, :min, :point_size, :reverse_axis, :show_categories, :smooth_line, :title_font_size, :tooltip_font_size, :tooltip_height, :tooltip_width, :width] end def string_options #:nodoc: [ :axis_color, :axis_background_color, :background_color, :border_color, :focus_border_color, :legend, :legend_background_color, :legend_text_color, :title, :title_x, :title_y, :title_color ] end def to_js #:nodoc: %{ <script type="text/javascript"> google.load('visualization', '1', {'packages':['linechart']}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); #{data_columns} #{data_table * "\r"} var options = {}; #{options} var container = document.getElementById('#{self.chart_element}'); var chart = new google.visualization.LineChart(container); chart.draw(data, options); } </script> } end # ====================================== Class Methods ========================================= def self.render(data, args) #:nodoc: graph = Seer::LineChart.new( :data => data, :series_label => args[:series][:series_label], :data_series => args[:series][:data_series], :data_label => args[:series][:data_label], :data_method => args[:series][:data_method], :chart_options => args[:chart_options], :chart_element => args[:in_element] || 'chart' ) graph.to_js end end end
ruby
MIT
2419e7a03a0cbf0c320b6cdfdcc902f6cf178709
2026-01-04T17:47:08.820980Z
false