text
stringlengths
10
2.61M
require 'test_helper' require 'support/redis_wrapper' class PrimaryKeyIndexTest < RelixTest include FamilyFixture def setup create_families end def test_reindex @talbotts.each{|t| t.family_key = "talbot"; t.index!} assert_equal @talbotts.collect{|e| e.key}.sort, Person.lookup{|q| q[:family_key].eq("talbot")}.sort assert_equal [], Person.lookup{|q| q[:family_key].eq(@talbott_family.key)} end def test_index_twice_with_same_primary_key first = @talbotts.first first.index! assert Person.lookup.include?(first.key) end def test_deindex assert Person.lookup.include?(@nathaniel.key), "expected index to include Nathaniel's key" @nathaniel.delete assert !Person.lookup.include?(@nathaniel.key), "expected index not to include Nathaniel's key" end def test_lookup_all assert_equal [@talbott_family.key, @omelia_family.key].sort, Family.lookup.sort end def test_lookup_by_primary_key assert_equal [@talbott_family.key], Family.lookup{|q| q[:key].eq('talbott')} assert_equal [@omelia_family.key], Family.lookup{|q| q[:key].eq('omelia')} end def test_count assert_equal 2, Family.lookup_count(:key) end def test_lookup_all_returns_in_insertion_order assert_equal @everyone.collect{|e| e.key}, Person.lookup end def test_offset_by_key assert_equal %w(katie reuben), Person.lookup{|q| q[:key].all(from: "nathaniel", limit: 2)} end def test_offset_by_missing_key assert_raise Relix::MissingIndexValueError do Person.lookup{|q| q[:key].all(from: "bogus", limit: 2)} end end def test_primary_key_not_stored_in_current_values redis_hash = Person.relix.current_values_name('nathaniel') current_values = Relix.redis.hgetall(redis_hash) assert !current_values.keys.include?('key'), 'expected the current values hash not to contain a duplicate of the primary key' end def primary_key_only_class Class.new do include Relix relix.primary_key :key relix.redis = RedisWrapper.new(relix.redis) attr_accessor :key def initialize(key); @key = key; index!; end end end def test_current_values_hash_not_stored_when_only_primary_key klass = primary_key_only_class klass.relix.redis.before(:hmset) do raise "hmset should not be called" end record = klass.new("foo") end end
class WeeklyWorkload < ActiveRecord::Base has_many :package_stats, :class_name => 'PackageStat', :foreign_key => 'weekly_workload_id', :dependent => :destroy, :order => 'user_id' has_many :auto_sum_details, :class_name => 'AutoSumDetail', :foreign_key => 'weekly_workload_id', :dependent => :destroy belongs_to :task default_value_for :manual_sum, 0 default_value_for :package_count, 0 end
class Public::SearchController < ApplicationController def search @value = params["search"]["value"] @how = params["search"]["how"] @target = params["search"]["target"] shops = search_for(@how, @value, @target) @shops = shops.page(params[:page]).per(5) end private def match(value, target) if target == "area" Shop.where(area_id: value) elsif target == "atmosphere" Shop.where(atmosphere_id: value) elsif value == "name" Shop.where(name: value) end end def partical(value) Shop.where("name LIKE ?", "%#{value}%") end def search_for(how, value, target) if how == 'match' match(value, target) else partical(value) end end end
# # プロンプト処理用 # # ログイン処理 def login(serial) puts "ログイン中..." serial.write "\n" loginFlag = false while !loginFlag do sleep 1 recv = "" loop do begin recv = recv + serial.readline if recv.include?("raspberrypi login:") # ユーザ名 serial.write "pi\n" break elsif recv.include?("Password:") # パスワード serial.write "raspberry\n" loginFlag = true break elsif recv.include?("pi@raspberrypi:~$") # ログイン済み(プロンプト受信) loginFlag = true break end rescue EOFError # readlineのエラー処理 end end end puts "ログイン完了" end # プロンプト受信待ち def waitPrompt(serial) serial.write "\n" recv = "" loop do begin recv = recv + serial.readline if recv.include?("pi@raspberrypi:~$") # プロンプトを受信 break end rescue EOFError # readlineのエラー処理 end end end
module StoreyValidator extend ActiveSupport::Concern included do validates :storey, numericality: { only_integer: true, greater_than: -1 } end end
require 'spec_helper' describe 'balloons/_form' do let(:balloon) { Balloon.new } before do view.stub(:balloon) { balloon } render end subject { rendered } it { should have_selector 'form' } it 'has the necessary form fields' do expect(rendered).to have_selector "input[name='balloon[name]']" expect(rendered).to have_selector "input[name='balloon[color]']" expect(rendered).to have_selector "input[name='balloon[altitude]']" expect(rendered).to have_selector "input[name='balloon[location]']" end end
create_table :user_password_authentications do |t| t.references :user, null: false, index: { unique: true, name: :idx_user_password_authentications_1, } t.string :password_digest, null: false end add_foreign_key :user_password_authentications, :users, name: :fk_user_password_authentications_1
class Appointment < ActiveRecord::Base belongs_to :doctor belongs_to :user validates :doctor_id, :date, :time, presence: true scope :most_recent, -> {Appointment.where('date < ?', Date.today).order(date: :desc).limit(1)} scope :next_appt, -> {Appointment.where('date > ?', Date.today).order(date: :asc).limit(1)} end
module Bb10Cli class Bb10Protocol DEFAULT_OPTIONS = {} USER_AGENT = 'QNXWebClient/1.0' COMMANDS = { TEST: 'test', INSTALL: 'Install', UNINSTALL: 'Uninstall', TERMINATE: 'Terminate', LAUNCH: 'Launch', INSTALL_AND_LAUNCH: 'Install and Launch', IS_RUNNING: 'Is Running', LIST: 'List', INSTALL_DEBUG_TOKEN: 'Install Debug Token', DEVICE_INFO: 'List Device Info', GET_FILE: 'Get File', PUT_FILE: 'Put File', VERIFY: 'Verify' } class HTTPClient include HTTParty_with_cookies end attr_reader :options def initialize(_options={}) @options = DEFAULT_OPTIONS.merge(_options) @verbose = @options[:cli][:verbose] @ip_address = @options[:ip_address] end def cookies @http_client.cookies end def do_query(path, query) @http_client ||= HTTPClient.new STDERR.puts ">>> GET: #{path} -> #{query.inspect}" if @verbose @http_client.get(File.join("https://#{@ip_address}/", path), query: query, headers: {'User-Agent' => USER_AGENT}, verify: false) end def do_post(path, query) multipart = Net::HTTP::Post::Multipart.new 'url.path', query body = multipart.body_stream.read.to_s @http_client ||= HTTPClient.new STDERR.puts ">>> POST: #{path} -> #{query.inspect}" if @verbose @http_client.post(File.join("https://#{@ip_address}/", path), body: body, headers: { 'User-Agent' => USER_AGENT, 'Content-Type' => 'multipart/form-data; boundary=-----------RubyMultipartPost' }, verify: false ) end def do_login(_password=nil) login_base_path = '/cgi-bin/login.cgi' password = _password || @options[:password] query_context = {request_version: 1} STDERR.puts '>>> Initial login request' if @verbose while (response = do_query(login_base_path, query_context)) do STDERR.puts "<<< Response: #{response.body.to_s}" if @verbose bb_response = response['RimTabletResponse'] case bb_response.values.first['Status'] when '*** Denied' STDERR.puts 'Login Denied' if @verbose return response when 'Error' STDERR.puts '*** Error' if @verbose return response when 'PasswdChallenge' STDERR.puts '*** Challenge' if @verbose challenge = bb_response['AuthChallenge']['Challenge'] algorithm = bb_response['AuthChallenge']['Algorithm'].to_i salt = bb_response['AuthChallenge']['Salt'] icount = bb_response['AuthChallenge']['ICount'].to_i saltbytes = [salt].pack('H*').bytes.to_a case algorithm.to_i when 2 STDERR.puts '*** V2 Login' if @verbose hash1 = hash_password(saltbytes, icount, password.bytes.to_a) hash2 = [] hash2 += challenge.bytes.to_a hash2 += hash1 hash2 = hash_password(saltbytes, icount, hash2) hex_encoded = to_hex(hash2) query_context[:challenge_data] = hex_encoded end when 'Success' STDERR.puts '*** Success' if @verbose if cookies['dtmauth'].nil? raise raise Exceptions::InvalidAuthCookieError end STDERR.puts if @verbose return response else STDERR.puts '*** Unknown problem logging in' if @verbose return response end STDERR.puts if @verbose end response end def do_command(cmd, _options={}) options = ({path: '/cgi-bin/appInstaller.cgi'}).merge(_options) command_base_path = options.delete(:path) args = {'dev_mode' => 'on'} args['command'] = COMMANDS[cmd] || cmd if cmd do_post(command_base_path, args.merge(options)) end protected def to_hex(buf) buf.pack('c*').unpack('H*').join.upcase end def hash_password(salt, iterations, password) data = password.dup iterations.times do |it| hash1 = [it].pack('L').bytes.to_a hash1 += salt hash1 += data d = Digest::SHA512.new d << hash1.pack('c*') data = d.digest.bytes.to_a end data end end end
require 'spec_helper' describe 'kmod::install', :type => :define do let(:title) { 'foo' } on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts.merge({ :augeasversion => '1.2.0', }) end let(:params) do { :ensure => 'present', :command => '/bin/true', :file => '/etc/modprobe.d/modprobe.conf' } end it { should contain_kmod__install('foo') } it { should contain_kmod__setting('kmod::install foo').with({ 'ensure' => 'present', 'category' => 'install', 'module' => 'foo', 'option' => 'command', 'value' => '/bin/true', 'file' => '/etc/modprobe.d/modprobe.conf' }) } end end end
require 'openssl' module Polydata class Key KeyBits = 2048 # msg bytes 245 # FIXME use this in key gen KeyGenDays = 730 def self.encrypt(keystr, msg) rsa_key = OpenSSL::PKey::RSA.new(keystr) raise( RuntimeError, "Message too large to encrypt.") if msg.size > 245 # FIXME use KeyBits math # "2048 bit key which gives 256 - 11 = 245 bytes" if rsa_key.private? rsa_key.private_encrypt(msg.to_s) # large msg is sloooow else rsa_key.public_encrypt(msg.to_s) # large msg is sloooow end end def self.decrypt(keystr, crypt) rsa_key = OpenSSL::PKey::RSA.new(keystr) if rsa_key.private? rsa_key.private_decrypt(crypt) elsif rsa_key.public? rsa_key.public_decrypt(crypt) else raise RuntimeError, "Bad key." end end =begin these are not used in polydata but I hesitate to trash them ... def self.sign(private_keystr, msg) # only works with private keys private_key = OpenSSL::PKey::RSA.new(private_keystr) raise(RuntimeError, "Only private keys can sign.") unless private_key.private? dig = OpenSSL::Digest::SHA1.new private_key.sign(dig, msg) end def self.verify(keystr, signed, unsigned) key = OpenSSL::PKey::RSA.new(keystr) dig = OpenSSL::Digest::SHA1.new key.verify(dig, signed, unsigned) end =end def self.generate_pair(tmp_path) # pri = `openssl genrsa 1024` # pub = `openssl req -new -utf8 -batch -pubkey -x509 -nodes -sha1 -days #{KeyGenDays} -key #{tmp_path}.pri` # pri key needs to be in a file which makes this awkward # FIXME there are cleaner ways to get the PEM values public_data = `openssl req -new -batch -x509 -pubkey -nodes -days #{KeyGenDays} -keyout #{tmp_path}.pri` # public_data contains a certificate request ix0 = public_data.index('-----BEGIN PUBLIC KEY-----') ix1 = public_data.index('-----END PUBLIC KEY-----') + 24 # -----END PUBLIC KEY----- is 24 chars private_key = '' File.new( "#{tmp_path}.pri", 'r' ).read(nil, private_key) keys = { :private_key => private_key, :public_key => public_data[ix0, (ix1 - ix0)] } `rm #{tmp_path}.pri` # FIXME data on file, even briefly, is a security hole? keys end end # /class Key end # /module Polydata
require './interface/renderer' require './interface/input' require './game/match' # Author: Roman Schmidt, Daniel Osterholz # # Create required classes, loop each Game if required, print exit in the end class Mastermind def initialize @renderer = Renderer.new @input = Input.new(@renderer) @match = Match.new(@renderer, @input) start end private def start begin @match.start_new @renderer.draw_play_again end while @input.get_play_again? stop end def stop @renderer.draw_bye exit(0) end end Mastermind.new
#!/usr/bin/env ruby # encoding: UTF-8 module NapakalakiGame class Prize =begin Constructor que crea y asigna las variables de instancia el primer valor sera el número de tesoros y el segundo será los niveles que gana el jugador al derrotar al mostruo =end def initialize(treasures, levels) @treasures = treasures @levels = levels end # Método to_s devuelve los variables de instacia en un String def to_s "\n\tNumero de tesoros: "+@treasures.to_s+"\n\tNiveles: "+@levels.to_s + "\n"#return end # Método para leer valores de variables de instancia attr_reader :treasures, :levels end end
class X0600h_title attr_reader :title, :options, :name, :field_type, :node def initialize @title = "Correction Request" @name = "Is this a SNF PPS Part A Discharge (End of Stay) Assessment? (X0600h)" @field_type = DROPDOWN @node = "X0600H_title" @options = [] @options << FieldOption.new("0", "No") @options << FieldOption.new("1", "Yes") end def set_values_for_type(klass) return "0" end end
require "json" module Util class Writer class << self def write file_name receiver = {} yield receiver if block_given? File.open file_name, "w" do |file| file.write JSON.pretty_generate(receiver) end end end end end
require 'spec_helper' require 'easy_mapper/adapters/postgre_adapter' require 'easy_mapper/model' RSpec.describe 'EasyMapper::Adapters::PostgreAdapter' do before(:all) do @adapter = EasyMapper::Adapters::PostgreAdapter.new( database: 'easy_mapper_test_db', user: 'easy_mapper_user', password: '' ) end describe 'connect' do it 'uses the config given on creation' do @adapter.connect end end end
require 'sinatra/base' module Sinatra module DataminerPortalHelpers extend Sinatra::Extension def sql_to_highlight(sql) # wrap sql @ 120 width = 120 ar = sql.gsub(/from /i, "\nFROM ").gsub(/where /i, "\nWHERE ").gsub(/(left outer join |left join |inner join |join )/i, "\n\\1").split("\n") wrapped_sql = ar.map {|a| a.scan(/\S.{0,#{width-2}}\S(?=\s|$)|\S+/).join("\n") }.join("\n") theme = Rouge::Themes::Github.new formatter = Rouge::Formatters::HTMLInline.new(theme) lexer = Rouge::Lexers::SQL.new formatter.format(lexer.lex(wrapped_sql)) end def yml_to_highlight(yml) theme = Rouge::Themes::Github.new formatter = Rouge::Formatters::HTMLInline.new(theme) lexer = Rouge::Lexers::YAML.new formatter.format(lexer.lex(yml)) end # TODO: Change this to work from filenames. def lookup_report(id) Crossbeams::DataminerPortal::DmReportLister.new(settings.dm_reports_location).get_report_by_id(id) end def clean_where(sql) rems = sql.scan( /\{(.+?)\}/).flatten.map {|s| "#{s}={#{s}}" } rems.each {|r| sql.gsub!(%r|and\s+#{r}|i,'') } rems.each {|r| sql.gsub!(r,'') } sql.sub!(/where\s*\(\s+\)/i, '') sql end def setup_report_with_parameters(rpt, params) #{"col"=>"users.department_id", "op"=>"=", "opText"=>"is", "val"=>"17", "text"=>"Finance", "caption"=>"Department"} input_parameters = ::JSON.parse(params[:json_var]) # logger.info input_parameters.inspect parms = [] # Check if this should become an IN parmeter (list of equal checks for a column. eq_sel = input_parameters.select { |p| p['op'] == '=' }.group_by { |p| p['col'] } in_sets = {} in_keys = [] eq_sel.each do |col, qp| in_keys << col if qp.length > 1 end input_parameters.each do |in_param| col = in_param['col'] if in_keys.include?(col) in_sets[col] ||= [] in_sets[col] << in_param['val'] next end param_def = @rpt.parameter_definition(col) if 'between' == in_param['op'] parms << Crossbeams::Dataminer::QueryParameter.new(col, Crossbeams::Dataminer::OperatorValue.new(in_param['op'], [in_param['val'], in_param['val_to']], param_def.data_type)) else parms << Crossbeams::Dataminer::QueryParameter.new(col, Crossbeams::Dataminer::OperatorValue.new(in_param['op'], in_param['val'], param_def.data_type)) end end in_sets.each do |col, vals| param_def = @rpt.parameter_definition(col) parms << Crossbeams::Dataminer::QueryParameter.new(col, Crossbeams::Dataminer::OperatorValue.new('in', vals, param_def.data_type)) end rpt.limit = params[:limit].to_i if params[:limit] != '' rpt.offset = params[:offset].to_i if params[:offset] != '' begin rpt.apply_params(parms) rescue StandardError => e return "ERROR: #{e.message}" end end def make_options(ar) ar.map do |a| if a.kind_of?(Array) "<option value=\"#{a.last}\">#{a.first}</option>" else "<option value=\"#{a}\">#{a}</option>" end end.join("\n") end def the_url_prefix settings.url_prefix end def menu(options = {}) admin_menu = options[:with_admin] ? " | <a href='/#{settings.url_prefix}admin'>Return to admin index</a>" : '' back_menu = options[:return_to_report] ? " | <a href='#{options[:return_action]}?back=y'>Back</a>" : '' "<p><a href='/#{settings.url_prefix}index'>Return to report index</a>#{admin_menu}#{back_menu}</p>" end def h(text) Rack::Utils.escape_html(text) end def select_options(value, opts, with_blank = true) ar = [] ar << "<option value=''></option>" if with_blank opts.each do |opt| if opt.kind_of? Array text, val = opt else val = opt text = opt end is_sel = val.to_s == value.to_s ar << "<option value='#{val}'#{is_sel ? ' selected' : ''}>#{text}</option>" end ar.join("\n") end def make_query_param_json(query_params) common_ops = [ ['is', "="], ['is not', "<>"], ['greater than', ">"], ['less than', "<"], ['greater than or equal to', ">="], ['less than or equal to', "<="], ['is blank', "is_null"], ['is NOT blank', "not_null"] ] text_ops = [ ['starts with', "starts_with"], ['ends with', "ends_with"], ['contains', "contains"] ] date_ops = [ ['between', "between"] ] # ar = [] qp_hash = {} query_params.each do |query_param| hs = {column: query_param.column, caption: query_param.caption, default_value: query_param.default_value, data_type: query_param.data_type, control_type: query_param.control_type} if query_param.control_type == :list hs[:operator] = common_ops if query_param.includes_list_options? hs[:list_values] = query_param.build_list.list_values else hs[:list_values] = query_param.build_list {|sql| Crossbeams::DataminerPortal::DB[sql].all.map {|r| r.values } }.list_values end elsif query_param.control_type == :daterange hs[:operator] = date_ops + common_ops else hs[:operator] = common_ops + text_ops end # ar << hs qp_hash[query_param.column] = hs end # ar.to_json qp_hash.to_json end end helpers DataminerPortalHelpers end
class Step < ActiveRecord::Base belongs_to :use_case has_many :flows, dependent: :destroy has_many :slices, through: :flows after_create :assign_custom_id validate :type, presence: true def assign_custom_id previous = self.class.where('id < ? and use_case_id = ?', self.id, use_case.id).order("id DESC").take if previous.nil? update_attributes(custom_id: "#{type.to_s[0]}F.#{use_case.id}.1") else update_attributes(custom_id: "#{type.to_s[0]}F.#{use_case.id}.#{(previous.custom_id.split('.')[2].to_i + 1).to_s}") end end def full_desc "#{self.custom_id} #{self.description}" end end
# encoding: binary # frozen_string_literal: true module RbNaCl # Serialization features shared across all "key-like" classes module Serializable def to_s to_bytes end def to_str to_bytes end # Inspect this key # # @return [String] a string representing this key def inspect "#<#{self.class}:#{Util.bin2hex(to_bytes)[0, 8]}>" end end end
class Issue < ActiveRecord::Base has_many :articles, :order => 'priority' belongs_to :front_page_image, :class_name => 'Image', :foreign_key => 'front_page_image' #Specific article classes for an issue can be added here has_many :other_news_articles, :class_name => 'Article', :conditions => ['priority > 0 AND priority < 30 AND priority != 6'], :order => 'priority' has_many :feature_articles, :class_name => 'Article', :conditions => ['priority >= 50'], :order => 'priority' validates_uniqueness_of :date #Get an array of all issue dates def self.get_dates find(:all, :order => 'date DESC').collect {|issue| issue.date } end #Note find_by_strdate finds first date <= date while find_by_strdate_short is exact def self.find_by_strdate(str_date) #find_by_date(Date.strptime(str_date, '%Y-%m-%d'), :order => 'date DESC') #debugger find(:first, :conditions => ['date <= ?', Date.strptime(str_date, '%Y-%m-%d')], :order => 'date DESC') end def self.find_by_strdate_short(str_date) find_by_date(Date.strptime(str_date, '%m-%d-%y')) end #Find the next issue def next Issue.find(:first, :conditions => ['date > ?', date], :order => 'date') end #Find the previous issue def prev Issue.find(:first, :conditions => ['date < ?', date], :order => 'date DESC') end #Find the last front_page_image def last_front_page_image Issue.find(:first, :conditions => ['date <= ? AND front_page_image', date], :order => 'date DESC').front_page_image end def self.latest Issue.find(:first, :order => 'date DESC') end #find one or more articles not necessarily confined to the particular issue. #def all_recent # iss = Issue.find_by_id(id).date # #debugger # Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', # :conditions => ['issues.date > ? AND issues.date <= ? AND priority > -200', # iss - 7, iss], :order => 'issues.date DESC, priority') #end def breaking_news_articles Article.find(:all, :conditions => ['issue_id = ? AND (priority <= 0 AND priority > -200)', id], :order => 'priority') end def top_news_articles Article.find(:all, :conditions => ['issue_id = ? AND (priority > 0 AND priority <= 5)', id], :order => 'priority') end def more_news_articles Article.find(:all, :conditions => ['issue_id = ? AND (priority > 6 AND priority < 20)', id], :order => 'priority') end def election_news_articles Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 20 AND priority < 25)', id], :order => 'priority') end def pr_news_articles Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 25 AND priority < 30)', id], :order => 'priority') end def news_recent iss = Issue.find_by_id(id).date #debugger Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', :conditions => ['issues.date > ? AND issues.date <= ? AND ((priority > -200 AND priority < 30 AND priority != 6) OR priority >= 90)', iss - 7, iss], :order => 'issues.date DESC, priority') end def cur_editorials Article.find(:all, :conditions => ['issue_id = ? AND priority = 6', id], :order => 'priority') end def cur_editorials_recent iss = Issue.find_by_id(id).date #debugger Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', :conditions => ['issues.date > ? AND issues.date <= ? AND priority = 6', iss - 7, iss], :order => 'issues.date DESC, priority') end #Find the last editorial def last_editorial iss = Issue.find_by_id(id).date #debugger Article.find(:first, :joins => 'inner join issues on articles.issue_id = issues.id', :conditions => ['issues.date <= ? AND priority = 6', iss], :order => 'issues.date DESC, priority') end def new_editorials Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 85 AND priority < 90)', id], :order => 'priority') end def new_editorials_recent iss = Issue.find_by_id(id).date #debugger Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', :conditions => ['issues.date > ? AND issues.date <= ? AND priority >= 85 AND priority < 90', iss - 7, iss], :order => 'issues.date DESC, priority') end def ed_cartoons Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 80 AND priority < 85)', id], :order => 'priority') end def ed_cartoons_recent iss = Issue.find_by_id(id).date #debugger Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', :conditions => ['issues.date > ? AND issues.date <= ? AND priority >= 80 AND priority < 85', iss - 7, iss], :order => 'issues.date DESC, priority') end #def cur_letters_to_the_editor # Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 40 AND priority < 45)', id], :order => 'priority') #end def opinion_articles # Added letters Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 40 AND priority < 50)', id], :order => 'priority') end def commentary_recent iss = Issue.find_by_id(id).date #debugger Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', :conditions => ['issues.date > ? AND issues.date <= ? AND priority >= 40 AND priority < 50', iss - 7, iss], :order => 'issues.date DESC, priority') end def columnists_articles Article.find(:all, :conditions => ['issue_id = ? AND ((priority >= 30 AND priority < 40) OR (priority >= 60 AND priority <= 65))', id], :order => 'priority') end def columnists_recent #added 65-69 iss = Issue.find_by_id(id).date #debugger Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', :conditions => ['issues.date > ? AND issues.date <= ? AND ((priority >= 30 AND priority < 40) OR (priority >= 60 AND priority < 70))', iss - 7, iss], :order => 'issues.date DESC, priority') end def home_garden_only Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 66 AND priority < 70)', id], :order => 'priority') end #removed arts calendar # def arts_articles Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 55 AND priority < 60)', id], :order => 'priority') end def obit_articles Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 90 AND priority < 92)', id], :order => 'priority') end #Used for all "events" def cur_calendars Article.find(:all, :conditions => ['issue_id = ? AND ((priority >= 50 AND priority < 55) OR (priority >= 70 AND priority < 75))', id], :order => 'priority') end def arts_calendars Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 50 AND priority < 55)', id], :order => 'priority') end def events_calendars Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 70 AND priority < 75)', id], :order => 'priority') end def events Article.find(:all, :conditions => ['issue_id = ? AND (priority >= 75 AND priority < 79)', id], :order => 'priority') end def arts_entertainment_recent # 9/11 includes home and events iss = Issue.find_by_id(id).date #debugger Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', :conditions => ['issues.date > ? AND issues.date <= ? AND priority >= 50 AND priority < 80', iss - 7, iss], :order => 'issues.date DESC, priority') end #following are all multi-issue #def editorials #Not currently used # iss = Issue.find_by_id(id).date # #debugger # Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', # :conditions => ['issues.date > ? AND issues.date <= ? AND (priority = 6 OR (priority >= 85 AND priority < 90))', iss - 7, iss], :order => 'issues.date DESC') #end #def home_garden # iss = Issue.find_by_id(id).date # #debugger # Article.find(:all, :joins => 'inner join issues on articles.issue_id = issues.id', # :conditions => ['issues.date > ? AND issues.date <= ? AND priority >= 60 AND priority < 70', # iss - 7, iss], :order => 'issues.date DESC, priority') #end end
class AddAttributesToMerchantOrders < ActiveRecord::Migration def change add_column :merchant_orders, :delivery_method, :string add_column :merchant_orders, :product_id, :integer end end
class Job < ActiveRecord::Base before_validation :preval before_create :not_too_many belongs_to :user validates :title, presence: :true, length: { maximum: 50 } validates :description, presence: :true, length: { maximum: 1000 } validates :url, length: { maximum: 100 } private def preval if self.title self.title = self.title.strip end if self.description self.description = self.description.strip end if self.url self.url = self.url.strip.delete(' ') if !self.url.blank? if !self.url.start_with?('http://') and !self.url.start_with?('https://') and !self.url.start_with?('www.') self.url = 'http://' + self.url end end end end def not_too_many count = Job.where(user_id: self.user_id, created_at: 1.hour.ago..DateTime.now).count count <= 10 end end
class IdentificationsController < ApplicationController before_action :set_identification, only: [:show, :edit, :update, :destroy] def expiring @expiring_passports = Identification.passports.where("expiration_date < ?", Date.today.to_date + 210) end # GET /identifications # GET /identifications.json def index @identifications = Identification.all end # GET /identifications/1 # GET /identifications/1.json def show end # GET /identifications/new def new @identification = Identification.new @identification.visa_type = "TOURIST" @identification.profile_id = params[:profile_id] respond_to do | format | format.html format.js { render 'remote_form'} end end # GET /identifications/1/edit def edit @identification.country = @identification.try(:country).try(:titleize) respond_to do | format | format.html format.js { render 'remote_form'} end end # POST /identifications # POST /identifications.json def create @identification = Identification.new(identification_params) @profile = @identification.try :profile respond_to do |format| if @identification.save notice = "#{@identification.foid_type} for #{@identification.profile.full_name} was successfully created." format.html { redirect_to identifications_path, flash: {identification_notice: notice}} format.json { render action: 'show', status: :created, location: @identification } # format.js { render "add_#{@identification.foid_type.try :downcase}" } format.js { render 'add_identification'} else format.html { render action: 'new' } format.json { render json: @identification.errors, status: :unprocessable_entity } format.js end end end def update respond_to do |format| if @identification.update(identification_params) notice = "#{@identification.foid_type} for #{@identification.profile.full_name} was successfully updated." #format.html { redirect_to identifications_path, flash: {identification_notice: notice}} format.html { redirect_to profile_path(@identification.profile)} format.json { head :no_content } format.js { render 'add_identification'} else if identification_params[:doc_image] format.html { render '/doc_image/new' } format.js { render '/doc_image/new' } else render action: 'edit' format.json { render json: @identification.errors, status: :unprocessable_entity } end end end end # DELETE /identifications/1 # DELETE /identifications/1.json def destroy @identification.destroy respond_to do |format| format.html { redirect_to identifications_url } format.json { head :no_content } format.js { render "delete_by_type" } end end private # Use callbacks to share common setup or constraints between actions. def set_identification @identification = Identification.find(params[:id]) @profile = @identification.try :profile end # Never trust parameters from the scary internet, only allow the white list through. def identification_params params.require(:identification).permit(:foid_type, :foid, :notes, :profile_id, :date_issued, :expiration_date, :issued_by, :description, :country, :sub_type, :visa_type, :entry_date, :max_stay, :doc_image) end end
class DropBookmarksTime < ActiveRecord::Migration def change remove_column :bookmarks, :time end end
require 'spec_helper' require 'app/presenters/ingredient_presenter' describe IngredientPresenter do let(:ingredient) { Factory(:ingredient) } it 'presents an ingredient with a root key' do expected = { 'ingredient' => { 'name' => ingredient.name, 'category' => ingredient.category, 'beers' => ingredient.beers_count } } hash = IngredientPresenter.present(ingredient, context: self) expect(hash).to eq(expected) end end describe IngredientsPresenter do let(:context) do double.tap do |d| allow(d).to receive(:params).and_return({}) end end before { 2.times { Factory(:ingredient) } } it 'presents a collection of ingredients' do ingredients = Ingredient.all expected = { 'count' => 2, 'ingredients' => [ IngredientPresenter.new(ingredients.first, context: context, root: nil).present, IngredientPresenter.new(ingredients.last, context: context, root: nil).present ] } presented = IngredientsPresenter.new(ingredients, context: context, root: nil).present expect(presented['count']).to eq(expected['count']) expect(presented['ingredients']).to match_array(expected['ingredients']) end end
class ChangeColumnMaxAttemptsName < ActiveRecord::Migration[5.2] def change rename_column :courses, :max_attemps, :max_attempts end end
class Room < ActiveRecord::Base belongs_to :project validates :project, :presence => true has_many :doors accepts_nested_attributes_for :project, :doors mount_uploader :picture, PictureUploader end
class AddIndexOnPageNameToSubscribers < ActiveRecord::Migration def change add_index :subscribers, :page_name end end
class CreateApplicant < ActiveRecord::Migration[5.2] def change create_table :applicants do |t| t.integer :recruiter_id, null: false t.string :name, null: false t.string :position, null: false t.string :status, null: false t.string :location, null: false t.string :method, null: false t.date :date t.boolean :traveling, null: false t.timestamps end add_index :applicants, :recruiter_id add_index :applicants, :name add_index :applicants, :position end end
Pod::Spec.new do |s| s.name = 'NekoeSample' s.version = '2.3.3' s.summary = 'nekoe sample' s.homepage = 'https://github.com/morou/NekoeSample' s.license = { :type => 'Commercial', :file => 'LICENSE' } s.author = { 'nekoe' => 'kazuhiro.nakae@gmail.com' } s.social_media_url = 'https://twitter.com' s.source = { :git => 'https://github.com/morou/NekoeSample.git', :tag => s.version.to_s } s.documentation_url = 'http://example.com' s.platform = :ios s.swift_version = '3.2' s.ios.deployment_target = '8.0' s.source_files = 'NekoeSample/Classes/**/*' end
require 'test_helper' class Apicast::SandboxTest < ActiveSupport::TestCase def setup @provider = stub(id: 16) @config = { shared_secret: 'SECRET', hosts: [ 'a.net', 'b.net' ] } end test 'config' do assert_raise(ArgumentError) do ::Apicast::Sandbox.new(stub(id: 16), shared_secret: 'stuff') end end test 'deploy exceptions' do sandbox = ::Apicast::Sandbox.new(@provider, shared_secret: 'foo', hosts: ['a.net']) sandbox.raise_exceptions = true stub_request(:get, 'http://a.net/deploy/foo?provider_id=16').to_timeout assert_raise HTTPClient::TimeoutError do sandbox.deploy end sandbox.raise_exceptions = false refute sandbox.deploy, 'should have failed' end test 'deploy failure' do sandbox = ::Apicast::Sandbox.new(@provider, @config) sandbox.raise_exceptions = true stub_request(:get, 'http://a.net/deploy/SECRET?provider_id=16').to_return(status: 200) stub_request(:get, 'http://b.net/deploy/SECRET?provider_id=16').to_return(status: 500) refute sandbox.deploy, 'deploy should have failed' end test 'deploy success' do stub_request(:get, 'http://a.net/deploy/SECRET?provider_id=16').to_return(status: 200) stub_request(:get, 'http://b.net/deploy/SECRET?provider_id=16').to_return(status: 200) sandbox = ::Apicast::Sandbox.new(@provider, @config) sandbox.raise_exceptions = true assert sandbox.deploy, 'deploy failed' end end
#!/usr/bin/env ruby # -*- coding: utf-8 -*- # Copyright (C) 2010,2011 Yasuhiro ABE <yasu@yasundial.org> @basedir = File.dirname($0) require 'rubygems' require 'bundler/setup' require 'yalt' include YALTools::CmdLine require 'optparse' def option_parser ret = { :filename => "-", :dbname => "", :unit => 15, :check_rev => false, :couch_label=>"", :couch_conf=>"", :debug=>false, :deep_debug => false } OptionParser.new do |opts| opts.banner = <<-EOF Usage: #{File::basename($0)} dbname [-f file] [-u num_of_unit] [-y yaml_file] [-x yaml_label] [-d] [-h]" #{File::basename($0)} is a tool to transfer a input json stream to the couchdb server via /bulk_docs. Each input line must have the complete JSON notation. This script outputs the failed document list. Example: input prepared json stream into the "example" db. $ cat a.json | #{File::basename($0)} -d example Example: copy all documents of the "example" db into another db named "example2." $ lsdocs example | #{File::basename($0)} example2 EOF opts.separator '' opts.on('-f', '--file file', "Set an input filename or '-'.") { |f| ret[:filename] = f if FileTest.exist?(f) ret[:filename] = f if f == "-" } opts.on('-u', '--unit num_of_unit', 'Set the num of processing unit (default: 15)') { |u| ret[:unit] = u.to_i } opts.on('-r', '--check_rev', "Set the '_rev' entry into each line before processing") { |l| ret[:check_rev] = l } opts.on('-y', '--yaml_conf filename', "Set yaml conf file") { |c| ret[:couch_conf] = c } opts.on('-x', '--yml_label label', "Set label name in the yaml conf file (default: default.user)") { |l| ret[:couch_label] = l } opts.on('-d', '--debug', 'Enable the debug mode') { |g| ret[:debug] = g } opts.on('--dd', 'Enable the debug mode of the Couch::Server instance') { |g| ret[:deep_debug] = g } opts.on_tail('-h', '--help', 'Show this message') { $stderr.puts opts exit(1) } begin opts.parse!(ARGV) ret[:dbname] = ARGV[0] if ARGV.length == 1 rescue $stderr.puts opts $stderr.puts $stderr.puts "[error] #{$!}" exit(1) end if ret[:dbname] == "" $stderr.puts opts exit(1) end if ret[:couch_label] == "" ret[:couch_label] = get_default_yaml_label() end if ret[:couch_conf] == "" ret[:couch_conf] = get_default_yaml_conf(@basedir) end end return ret end @opts = option_parser msg = {"debug"=>@opts} and $stderr.puts msg.to_json if @opts[:debug] @couch = getCouch(@opts[:couch_conf], @opts[:couch_label], @opts[:deep_debug]) begin failed_list = [] lines = YALTools::YaJsonRows.new(@couch, @opts[:dbname]) load_line(@opts[:filename]) do |line| lines << line if lines.length == @opts[:unit] failed_list += lines.update_all end end if lines.size > 0 failed_list += lines.update_all end failed_list.each do |i| puts i.to_json end exit(0) rescue msg = {"error" => "undefined", "reason" => "unknown"} $stderr.puts msg.to_json $stderr.puts $! if @opts[:debug] end
class DatasetImplementationsController < ApplicationController before_filter :require_user # GET /dataset_implementations # GET /dataset_implementations.xml def index @page_title = "Implmentations of VDW Datasets" @dataset_implementations = DatasetImplementation.all(:order => "site_id, dataset_id") respond_to do |format| format.html # index.html.erb format.xml { render :xml => @dataset_implementations } end end # GET /dataset_implementations/1 # GET /dataset_implementations/1.xml def show @dataset_implementation = DatasetImplementation.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @dataset_implementation } end end # GET /dataset_implementations/new # GET /dataset_implementations/new.xml def new @dataset_implementation = DatasetImplementation.new @dataset_implementation.site_id = params[:site_id] unless params[:site_id].blank? @dataset_implementation.dataset_id = params[:dataset_id] unless params[:dataset_id].blank? respond_to do |format| format.html # new.html.erb format.xml { render :xml => @dataset_implementation } end end # GET /dataset_implementations/1/edit def edit @dataset_implementation = DatasetImplementation.find(params[:id]) end # POST /dataset_implementations # POST /dataset_implementations.xml def create @dataset_implementation = DatasetImplementation.new(params[:dataset_implementation]) respond_to do |format| if @dataset_implementation.save flash[:notice] = 'DatasetImplementation was successfully created.' format.html { redirect_to(@dataset_implementation) } format.xml { render :xml => @dataset_implementation, :status => :created, :location => @dataset_implementation } else format.html { render :action => "new" } format.xml { render :xml => @dataset_implementation.errors, :status => :unprocessable_entity } end end end # PUT /dataset_implementations/1 # PUT /dataset_implementations/1.xml def update @dataset_implementation = DatasetImplementation.find(params[:id]) respond_to do |format| if @dataset_implementation.update_attributes(params[:dataset_implementation]) flash[:notice] = 'DatasetImplementation was successfully updated.' format.html { redirect_to(@dataset_implementation) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @dataset_implementation.errors, :status => :unprocessable_entity } end end end # DELETE /dataset_implementations/1 # DELETE /dataset_implementations/1.xml def destroy @dataset_implementation = DatasetImplementation.find(params[:id]) @dataset_implementation.destroy respond_to do |format| format.html { redirect_to(dataset_implementations_url) } format.xml { head :ok } end end end
class Procedure < ApplicationRecord belongs_to :category, :class_name => :"ProcedureCategory", foreign_key: "procedure_category_id" end
require "rails_helper" require "support/helpers/googleapis_helper" RSpec.shared_examples "successful failure" do it "returns true" do expect(subject).to be true end it "updates failed_at" do expect { subject }.to change { deployment.reload.failed_at } end end RSpec.shared_examples "skipped failure" do it "returns false" do expect(subject).to be false end it "doesn't update failed_at" do expect { subject }.not_to change { deployment.reload.failed_at } end it "doesn't update fail_message" do expect { subject }.not_to change { deployment.reload.fail_message } end end RSpec.describe Deployment, type: :model do include GoogleapisHelper describe "#valid?" do subject { deployment.valid? } context "when attributes are valid" do let(:deployment) { build(:deployment) } it { is_expected.to be true } end context "when project is nil" do let(:deployment) { build(:deployment, project: nil) } it { is_expected.to be false } end context "when instance is blank" do let(:deployment) { build(:deployment, instance: " ") } it { is_expected.to be false } end end describe "#pending?" do subject { deployment.pending? } context "when finished? is true" do context "when failed? is true" do let(:deployment) { build(:deployment, :finished, :failed) } it { is_expected.to be false } end context "when failed? is false" do let(:deployment) { build(:deployment, :finished) } it { is_expected.to be false } end end context "when finished? is false" do context "when failed? is true" do let(:deployment) { build(:deployment, :failed) } it { is_expected.to be false } end context "when failed? is false" do let(:deployment) { build(:deployment) } it { is_expected.to be true } end end end describe "#finished?" do subject { deployment.finished? } context "when finished_at is not nil" do let(:deployment) { build(:deployment, finished_at: Time.current) } it { is_expected.to be true } end context "when finished_at is nil" do let(:deployment) { build(:deployment, finished_at: nil) } it { is_expected.to be false } end end describe "#failed?" do subject { deployment.failed? } context "when failed_at is not nil" do let(:deployment) { build(:deployment, failed_at: Time.current) } it { is_expected.to be true } end context "when failed_at is nil" do let(:deployment) { build(:deployment, failed_at: nil) } it { is_expected.to be false } end end describe "#handle_success" do let(:deployment) { create(:deployment) } subject { deployment.handle_success(DateTime.parse("1970-01-01T00:00:00.000Z")) } it "updates finished_at" do expect { subject }.to change { deployment.reload.finished_at.to_s }.to("1970-01-01 00:00:00 UTC") end end describe "#handle_failure" do subject { deployment.handle_failure("foo") } context "when pending? is true" do let(:deployment) { create(:deployment, :pending) } include_examples "successful failure" it "updates fail_message" do expect { subject }.to change { deployment.reload.fail_message }.to("foo") end end context "when pending? is false" do let(:deployment) { create(:deployment, :failed) } include_examples "skipped failure" end end describe "#handle_timeout" do let(:compute_engine) { class_double(ComputeEngine).as_stubbed_const } before { allow(compute_engine).to receive(:delete_instance) } subject { deployment.handle_timeout } context "when pending? is true" do let(:deployment) { create(:deployment, :pending, instance: "foo") } include_examples "successful failure" it "updates fail_message" do expect { subject }.to change { deployment.reload.fail_message }.to("Timeout") end it "calls ComputeEngine.delete_instance" do expect(compute_engine).to receive(:delete_instance).with("foo") subject end end context "when pending? is false" do let(:deployment) { create(:deployment, :finished, instance: "foo") } include_examples "skipped failure" it "doesn't call ComputeEngine.delete_instance" do expect(compute_engine).not_to receive(:delete_instance) subject end end end end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" puts <<eof Hello, Puppetry! eof $post = <<SCRIPT sudo service nginx restart sudo service php5-fpm restart SCRIPT Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.hostname = "dev.puppetry.com" config.vm.box = "ubuntu/trusty64" config.vm.define "developer", primary: true do |developer| developer.vm.synced_folder "developer", "/var/www", :nfs => { :mount_options => ["dmode=777, fmode=666"] } developer.vm.network "forwarded_port", guest: 8000, host: 8506 developer.vm.network "private_network", ip: "192.168.1.99" developer.vm.provision "puppet" do |puppet| puppet.module_path = "puppet/modules" puppet.manifests_path = "puppet" puppet.manifest_file = "manifests/dev.pp" # puppet.hiera_config_path = "hiera.yaml" # puppet.working_directory = "/tmp/vagrant-puppet-2" # puppet.options = "--verbose --debug" end developer.vm.provision "shell", inline: $post, privileged: false end config.vm.define "integration", primary: true do |integration| integration.vm.synced_folder "integration", "/var/www", :nfs => { :mount_options => ["dmode=777, fmode=666"] } integration.vm.network "forwarded_port", guest: 8000, host: 8507 integration.vm.network "private_network", ip: "192.168.1.100" integration.vm.provision "puppet" do |puppet| puppet.module_path = "puppet/modules" puppet.manifests_path = "puppet" puppet.manifest_file = "manifests/integration.pp" end integration.vm.provision "shell", inline: $post, privileged: false end config.vm.define "staging", primary: true do |staging| staging.vm.synced_folder "staging", "/var/www", :nfs => { :mount_options => ["dmode=777, fmode=666"] } staging.vm.network "forwarded_port", guest: 8000, host: 8508 staging.vm.network "private_network", ip: "192.168.1.101" staging.vm.provision "puppet" do |puppet| puppet.module_path = "puppet/modules" puppet.manifests_path = "puppet" puppet.manifest_file = "manifests/staging.pp" end staging.vm.provision "shell", inline: $post, privileged: false end config.vm.define "production", primary: true do |production| production.vm.synced_folder "production", "/var/www", :nfs => { :mount_options => ["dmode=777, fmode=666"] } production.vm.network "forwarded_port", guest: 8000, host: 8509 production.vm.network "private_network", ip: "192.168.1.102" production.vm.provision "puppet" do |puppet| puppet.module_path = "puppet/modules" puppet.manifests_path = "puppet" puppet.manifest_file = "manifests/production.pp" end production.vm.provision "shell", inline: $post, privileged: false end end
#======================================================================================================================= # Git #======================================================================================================================= # ダウンロード resource_file_path = "#{Chef::Config[:file_cache_path]}/git-2.7.0.tar.gz" remote_file resource_file_path do source "https://github.com/git/git/archive/v2.7.0.tar.gz" end # 展開 bash "git::extract" do code "tar -xz --no-same-owner --no-same-permissions -f #{resource_file_path} -C /opt" not_if "test -d /opt/git-2.7.0" end # ビルド/インストール bash "git::install" do cwd "/opt/git-2.7.0" code <<-EOC make configure ./configure --prefix=${PWD} make all make install EOC not_if "test -d /opt/git-2.7.0/bin" end # 環境設定 ruby_block "git::env" do block do ENV['GIT_HOME'] = "/opt/git-2.7.0" ENV['PATH'] = "#{ENV['GIT_HOME']}/bin:#{ENV['PATH']}" end not_if { ENV['GIT_HOME'] == "/opt/git-2.7.0" } end template "/etc/profile.d/git.sh" link "/etc/profile.d/git-prompt.sh" do to "/opt/git-2.7.0/contrib/completion/git-prompt.sh" end link "/etc/bash_completion.d/git" do to "/opt/git-2.7.0/contrib/completion/git-completion.bash" end
def mxdiflg(a1, a2) return -1 if a1.empty? || a2.empty? min1, max1 = a1.map(&:size).minmax min2, max2 = a2.map(&:size).minmax [max1 - min2, max2 - min1].max end
#encoding: UTF-8 class EducationalProgramsController < ApplicationController skip_before_action :authenticate_user!, only: [:show] before_action :require_moderator, only: [:new, :edit, :update, :create, :destroy] before_action :set_educational_program, only: [:show, :edit, :destroy, :update] before_action :educational_program_params, only: [:create, :update] before_action :options_for_select, only: [:new, :edit, :update] def index @educational_programs = EducationalProgram.order('level DESC').order([:code, :name]) end def show @methodological_supports = @educational_program.methodological_supports.includes(:attachment).sort_by{|ms| ms.attachment.title} @subjects = @educational_program.subjects.order(:name) @methodological_support = MethodologicalSupport.new @attachments = Attachment.order(:title).select(:id, :title).select{|a| a.title =~ /pdf/} end def new @educational_program = EducationalProgram.new end def create @educational_program = EducationalProgram.new(educational_program_params) if @educational_program.save! redirect_to @educational_program, notice: "New program added successfully" else render action: 'new' end end def update if @educational_program.update(educational_program_params) redirect_to @educational_program else render action: 'edit' end end def destroy @educational_program.toggle!(:active) if @educational_program.active redirect_to educational_programs_url end private def set_educational_program @educational_program = EducationalProgram.find(params[:id]) end def educational_program_params params.require(:educational_program).permit(:id, :name, :code, :level, :form, :duration, :educational_standart_id, :accreditation_id, :attachment_id, :active, :language, :adaptive) end def options_for_select @educational_standarts = EducationalStandart.order(:level, :name).load @accreditations = Accreditation.order('date_of_issue DESC').load @attachments = Attachment.order(:title).select(:id, :title).select{|a| a.title =~ /pdf/} end end
# frozen_string_literal: true module DatadogLogStashPlugin VERSION = '0.5.1' end
class AdminController < ApplicationController layout "admin" before_action :authenticate_admin private # TODO: users have roles, duh def authenticate_admin authenticate_or_request_with_http_basic('Administration') do |username, password| username == 'stingadmin' && password == 'finley' end end end
require 'rubygems' require '4store-ruby' require 'uri' require 'json' require 'net/http' module DbpediaFinder class Finder def initialize @store = FourStore::Store.new 'http://dbpedia.org/sparql' @proxy = URI.parse(ENV['HTTP_PROXY']) if ENV['HTTP_PROXY'] end def find(label, disambiguation = nil) results = google_search(label, disambiguation) results.each do |uri| dbpedia = wikipedia_to_dbpedia(uri) next if dbpedia.split('Category:').size > 1 query = " PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT DISTINCT ?label WHERE { <#{dbpedia}> rdfs:label ?label FILTER ( regex(?label, '#{clean_label(label)}', 'i') ) } " match = @store.select query return [match[0]['label'], dbpedia] if match.size > 0 end return nil end def google_search(label, disambiguation) if disambiguation query = "\"#{label}\" #{disambiguation} site:en.wikipedia.org" else query = "\"#{label}\" site:en.wikipedia.org" end query = URI.encode(query) google_url_s = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=#{query}" url = URI.parse(google_url_s) if @proxy h = Net::HTTP::Proxy(@proxy.host, @proxy.port).new(url.host, url.port) else h = Net::HTTP.new(url.host, url.port) end h.start do |h| res = h.get(url.path + "?" + url.query) json = JSON.parse(res.body) results = json["responseData"]["results"].map { |result| result["url"] } return results end end def wikipedia_to_dbpedia(wikipedia) url_key = wikipedia.split('/').last return "http://dbpedia.org/resource/" + url_key end def clean_label(label) # Remove initials (as they are expanded in Wikipedia/DBpedia labels) cleaned_label = label.split(' ').select { |l| l.split('.').size == 1 }.join(' ') cleaned_label = cleaned_label.split("'").join("\\'") cleaned_label end end end
require 'spec_helper' describe ETL::DbfLoader do let(:new_forms_dbf) { "spec/data/TEST_EMPTY.DBF" } let(:subject) { create(:subject, subject_code: "3227GX", admit_date: Time.zone.local(2012, 3, 4)) } let(:source) { create(:source) } let(:documentation) { create(:documentation) } before do @new_forms_params = { conditional_columns: [2, 3], static_params: {}, event_groups: [ [:in_bed_start_scheduled, :in_bed_end_scheduled], [:out_of_bed_start_scheduled, :out_of_bed_end_scheduled], [:sleep_start_scheduled, :sleep_end_scheduled], [:wake_start_scheduled, :wake_end_scheduled], [:lighting_block_start_scheduled, :lighting_block_end_scheduled] ], conditions: { [/In Bed/, /005/] => { event_map: [ {name: :in_bed_start_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :out_of_bed_end_scheduled, existing_records: :destroy, labtime_fn: :from_s} ], column_map: [ {target: :event, field: :labtime}, {target: :event, field: :labtime_sec}, {target: :none}, {target: :none}, {target: :subject_code_verification}], capture_map: [] }, [/Out of Bed/, /005/] => { event_map: [{name: :out_of_bed_start_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :in_bed_end_scheduled, existing_records: :destroy, labtime_fn: :from_s}], column_map: [{target: :event, field: :labtime}, {target: :event, field: :labtime_sec}, {target: :none}, {target: :none}, {target: :subject_code_verification}], capture_map: [] }, [/Lighting Change Lux=(\d+)/, /024/] => { event_map: [{name: :lighting_block_start_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :lighting_block_end_scheduled, existing_records: :destroy, labtime_fn: :from_s}], column_map: [{target: :event, field: :labtime}, {target: :event, field: :labtime_sec}, {target: :none}, {target: :none}, {target: :subject_code_verification}], capture_map: [{target: :datum, name: :lighting_block_start_scheduled, field: :light_level}] }, [/Sleep Episode #(\d+) Lux=(\d+)/, /022/] => { event_map: [{name: :lighting_block_start_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :sleep_start_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :sleep_end_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :lighting_block_end_scheduled, existing_records: :destroy, labtime_fn: :from_s}], column_map: [{target: :event, field: :labtime}, {target: :event, field: :labtime_sec}, {target: :none}, {target: :none}, {target: :subject_code_verification}], capture_map: [ {target: :datum, name: :sleep_start_scheduled, field: :episode_number}, {target: :datum, name: :lighting_block_start_scheduled, field: :light_level} ] }, [/Wake Time #(\d+) Lux=(\d+)/, /023/] => { event_map: [{name: :lighting_block_start_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :wake_start_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :wake_end_scheduled, existing_records: :destroy, labtime_fn: :from_s}, {name: :lighting_block_end_scheduled, existing_records: :destroy, labtime_fn: :from_s}], column_map: [{target: :event, field: :labtime}, {target: :event, field: :labtime_sec}, {target: :none}, {target: :none}, {target: :subject_code_verification}], capture_map: [ {target: :datum, name: :wake_start_scheduled, field: :episode_number}, {target: :datum, name: :lighting_block_start_scheduled, field: :light_level} ] }, [] => { event_map: [{name: :new_forms_event, existing_records: :destroy, labtime_fn: :from_s}], column_map: [{target: :event, field: :labtime}, {target: :event, field: :labtime_sec}, {target: :datum, field: :event_description}, {target: :datum, field: :event_code}, {target: :subject_code_verification}], capture_map: [] } } } create(:dbf_loader_dictionaries) end it "should correctly load TEST_EMPTY.DBF file" do dbf_loader = ETL::DbfLoader.new(new_forms_dbf, @new_forms_params, source, documentation, subject) dbf_loader.load Event.where("group_label is not null").count.should == Event.where("name != ?", "new_forms_event").count Subject.count.should == 1 Event.where(name: "in_bed_start_scheduled").count.should == 5 Event.where(name: "in_bed_end_scheduled").count.should == 5 Event.where(name: "out_of_bed_start_scheduled").count.should == 5 Event.where(name: "out_of_bed_end_scheduled").count.should == 5 Event.where(name: "sleep_start_scheduled").count.should == 5 Event.where(name: "sleep_end_scheduled").count.should == 5 Event.where(name: "wake_start_scheduled").count.should == 5 Event.where(name: "wake_end_scheduled").count.should == 5 Event.where(name: "lighting_block_start_scheduled").count.should == 11 Event.where(name: "lighting_block_end_scheduled").count.should == 11 Event.where(name: "new_forms_event").count.should == 746 end it "should not duplicate events if existing records are set to be destroyed" do dbf_loader = ETL::DbfLoader.new(new_forms_dbf, @new_forms_params, source, documentation, subject) dbf_loader.load event_count = Event.count event_count.should_not == 0 dbf_loader2 = ETL::DbfLoader.new(new_forms_dbf, @new_forms_params.clone, source, documentation, subject) dbf_loader2.load Event.count.should == event_count end end
Rails.application.routes.draw do #For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get '/', to: 'gossips#index', as: 'root' resources :gossips do resources :comments, except: [:index, :new] do resources :comments, except: [:index, :new] end end resources :welcome, only: [:show] resources :user, only: [:show, :create, :new] resources :sessions, only: [:show, :create, :new, :destroy] resources :city, only: [:show] resources :contact, only: [:index] resources :team, only: [:index] resources :likes, only: [:create, :destroy] resources :tags end
require 'formula' class LibbitcoinExamples < Formula homepage 'https://github.com/spesmilo/libbitcoin' url 'https://github.com/spesmilo/libbitcoin.git', :tag => 'v1.4' depends_on 'WyseNynja/bitcoin/boost-gcc48' depends_on 'WyseNynja/bitcoin/libbitcoin' depends_on 'watch' def patches # lboost_thread is named differently on osx DATA end def install ENV['CC']= "gcc-4.8" ENV['CXX'] = "g++-4.8" ENV['LD'] = ENV['CXX'] ENV['CPPFLAGS'] = "-I/usr/local/opt/libbitcoin/include -I/usr/local/opt/boost-gcc48/include -I/usr/local/opt/leveldb-gcc48/include" ENV['LDFLAGS'] = "-L/usr/local/opt/libbitcoin/lib -L/usr/local/opt/boost-gcc48/lib -L/usr/local/opt/leveldb-gcc48/lib" cd "examples" do system "make" for script in [ "accept", "balance", "blocks.sh", "connect", "determ", "display-last", "fullnode", "initchain", "priv", "proto", "satoshiwords", "txrad", ] do system "mv", script, "bitcoin-"+script bin.install "bitcoin-"+script end end end test do # This test will fail and we won't accept that! It's enough to just replace # "false" with the main program this formula installs, but it'd be nice if you # were more thorough. Run the test with `brew test libbitcoin`. system "false" end end __END__ diff --git a/examples/Makefile b/examples/Makefile index aa7fa9d..b2a6f68 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -1,5 +1,5 @@ -CXXFLAGS=$(shell pkg-config --cflags libbitcoin) -ggdb -LIBS=$(shell pkg-config --libs libbitcoin) +CXXFLAGS=$(shell pkg-config --cflags libbitcoin) -ggdb -I/usr/local/opt/boost-gcc48/include -I/usr/local/opt/curl/include -I/usr/local/opt/leveldb-gcc48/include +LIBS=$(shell pkg-config --libs libbitcoin) -L/usr/local/opt/boost-gcc48/lib -L/usr/local/opt/curl/lib -L/usr/local/opt/leveldb-gcc48/lib default: all
class CreateRents < ActiveRecord::Migration def change create_table :rents do |t| t.integer :user_id t.integer :kunstvoorwerp_id t.integer :prijs t.boolean :status t.timestamps end add_index :rents, :user_id add_index :rents, :kunstvoorwerp_id end end
class GolpherService attr_reader :server def initialize config options = config.symbolize_keys.merge(default_server_options) @server = Server.new options end def start Thread.new { server.run } end def stop server.stop end private def processor MessageProcessor.new success_handler: list_messages_queue, failure_handler: failed_message_queue end def list_messages_queue TorqueBox::Messaging::Queue.new('/queues/mail_lists') end def failed_message_queue TorqueBox::Messaging::Queue.new('/queues/failed_mail') end def default_server_options { processor: processor, logger: Rails.logger } end end
# frozen_string_literal: true require('lox/cli') require('lox/console') require('lox/formatter') require('lox/lexical_analyzer') require('lox/scanner') require('lox/write') require('readline') RSpec.describe(Lox::CLI) do subject :cli do described_class.new end let :formatter do instance_double(Lox::Formatter) end let :command do instance_spy(Lox::Write) end before do allow(Lox::Write).to(receive(:new).with(formatter, STDOUT)) do command end end describe '#read' do subject :read do cli.read end let :console do instance_double(Lox::Console, each_line: each_line) end let :each_line do instance_double(Enumerator) end before do allow(Lox::Console).to(receive(:new).with(Readline)) do console end allow(Lox::Formatter).to(receive(:new).with(each_line)) do formatter end end it 'writes lines to standard output' do read expect(command).to(have_received(:call)) end end describe '#scan' do subject :scan do cli.scan end let :console do instance_double(Lox::Console) end let :scanner do instance_double(Lox::Scanner, each_char: each_char) end let :each_char do instance_double(Enumerator) end before do allow(Lox::Console).to(receive(:new)) do console end allow(Lox::Scanner).to(receive(:new).with(console)) do scanner end allow(Lox::Formatter).to(receive(:new).with(each_char)) do formatter end end it 'writes characters to standard output' do scan expect(command).to(have_received(:call)) end end describe '#lex' do subject :lex do cli.lex end let :scanner do instance_double(Lox::Scanner) end let :lexical_analyzer do instance_double(Lox::LexicalAnalyzer, each_token: each_token) end let :each_token do instance_double(Enumerator) end before do allow(Lox::Scanner).to(receive(:new)) do scanner end allow(Lox::LexicalAnalyzer).to(receive(:new).with(scanner)) do lexical_analyzer end allow(Lox::Formatter).to(receive(:new).with(each_token)) do formatter end end it 'writes tokens to standard output' do lex expect(command).to(have_received(:call)) end end end
class UsersController < ApplicationController def show @user = User.find params[:id] authorize @user respond_to do |format| format.json { render json: current_user.to_json } format.html end end def current authorize current_user, :show? respond_to do |format| format.json { render json: current_user.to_json } format.html { redirect_to current_user } end end end
class RenameRoleOfInvoice < ActiveRecord::Migration def self.up rename_column :invoices, :type, :i_type add_column :invoice_items, :product_number, :string end def self.down rename_column :invoices, :i_type, :type remove_column :invoice_items, :product_number end end
And(/^attempts to make a payment$/) do visit(PaymentsDetailsPage) on(PaymentsDetailsPage).wait_for_page_to_load end Then(/^the customer is directed to the feature unavailable page with the payments messages$/) do on(FeatureUnavailablePage).title.should eq @feature_unavailable_data['feature_unavailable_title'] on(FeatureUnavailablePage).page_header.should eq @feature_unavailable_data['feature_unavailable_header'] on(FeatureUnavailablePage).text.gsub!(/\s+/, ' ').should include @feature_unavailable_data['canadian_payment_feature_unavailable_message'] end Then(/^the customer will not have an option to navigate to payments$/) do #on(NavigationBar).payments?.should be false on(NavigationBar).text.should_not include 'Payments' on(NavigationBar).text.should_not include 'Make a Payment' end When(/^the user is attempting to view payment activity$/) do visit(PaymentActivityPage) on(NavigationBar).wait_for_angular_ajax sleep 5 end Then(/^the customer is directed to the feature unavailable page with result code of 8683$/) do on(FeatureUnavailablePage).title.should eq @feature_unavailable_data['canadian_payment_activity_feature_unavailable_title'] on(FeatureUnavailablePage).page_header.should eq @feature_unavailable_data['feature_unavailable_header'] on(FeatureUnavailablePage).text.gsub!(/\s+/, ' ').should include @feature_unavailable_data['canadian_payment_activity_feature_unavailable_message'] end
class TagAssignmentsController < ApplicationController # before_action :verify_user_by_course, only: [:new, :destroy] before_action :verify_user_by_course, only: [:create] before_action :check_ownership, only: [:destroy] def create @tag_assignment = @course.tag_assignments.create(tag_assignment_params) end def destroy #TagAssignment.destroy(params[:id]) #TODO TRYING THIS TO SEE IF IT SOLVES THE DESTROY PROBLEM WHEN DEPLOYED @tag_assignment.destroy #TODO end private # Never trust parameters from the scary internet, only allow the white list through. def tag_assignment_params #params.require(:tag_assignment).permit(:tag_id, :assignment_id) params.require(:tag_assignment).permit(:course_id, :tag_id, :assignment_id) end def check_ownership @course = Course.find(TagAssignment.find(params[:id]).course_id) #finds the correct user associated with this course and compares it to the current user correct_user_id=@course.user_id redirect_to(signin_url, notice:'Incorrect User') unless current_user.id==correct_user_id end end
# require 'rails_helper' # # RSpec.describe TestsController, type: :controller do # let(:valid_attributes) do # FactoryBot.attributes_for :test # end # # let(:invalid_attributes) do # FactoryBot.attributes_for :test, # test_amount: nil, # test_unit_of_meas: nil, # topic_id: nil # end # # let(:valid_session) { {} } # # describe 'GET #index' do # let(:test) { FactoryBot.create :test } # # it 'assigns all tests as @tests' do # get :index, {} # expect(assigns(:tests)).to eq [test] # end # end # # describe 'GET #show' do # let(:test) { FactoryBot.create :test } # # it 'assigns the requested test as @test' do # get :show, params: { id: test.to_param } # expect(assigns(:test)).to eq test # end # end # # describe 'GET #new' do # it 'assigns a new test as @test' do # get :new, {} # expect(assigns(:test)).to be_a_new Test # end # end # # describe 'GET #edit' do # let(:test) { FactoryBot.create :test } # # it 'assigns the requested test as @test' do # get :edit, params: { id: test.to_param } # expect(assigns(:test)).to eq test # end # end # # describe 'POST #create' do # context 'with valid params' do # it 'creates a new Test' do # expect { # post :create, params: { test: valid_attributes } # }.to change(Test, :count).by 1 # end # # it 'assigns a newly created test as @test' do # post :create, params: { test: valid_attributes } # expect(assigns(:test)).to be_a Test # expect(assigns(:test)).to be_persisted # end # # it 'redirects to the created test' do # post :create, params: { test: valid_attributes } # expect(response).to redirect_to Test.last # end # end # # context 'with invalid params' do # it 'assigns a newly created but unsaved test as @test' do # post :create, params: { test: invalid_attributes } # expect(assigns(:test)).to be_a_new(Test) # end # # it 're-renders the \'new\' template' do # post :create, params: { test: invalid_attributes } # expect(response).to render_template 'new' # end # end # end # # describe 'PUT #update' do # context 'with valid params' do # let(:test) { FactoryBot.create :test } # # it 'updates the requested test' do # put :update, params: { id: test.to_param, test: new_attributes } # test.reload # skip('Add assertions for updated state') # end # # it 'assigns the requested test as @test' do # put :update, params: { id: test.to_param, test: valid_attributes } # expect(assigns(:test)).to eq test # end # # it 'redirects to the test' do # put :update, params: { id: test.to_param, test: valid_attributes } # expect(response).to redirect_to test # end # end # # context 'with invalid params' do # let(:test) do # FactoryBot.create :test, # patient: nil # end # # it 'assigns the test as @test' do # put :update, params: { id: test.to_param, test: test } # expect(assigns(:test)).to eq test # end # # it 're-renders the \'edit\' template' do # put :update, params: { id: test.to_param, test: test} # expect(response).to render_template 'edit' # end # end # end # # describe 'DELETE #destroy' do # let(:test) { FactoryBot.create :test } # # it 'destroys the requested test' do # expect { # delete :destroy, params: { id: test.to_param } # }.to change(Test, :count).by(-1) # end # # it 'redirects to the tests list' do # delete :destroy, params: { id: test.to_param } # expect(response).to redirect_to(tests_url) # end # end # end
class TripController < ApplicationController get '/trips' do @trips = Trip.all.sort_by{|trip| trip.name} erb :'trips/index' end end
require 'rubygems' require 'active_record' require 'sys/admin' class ActsAsProtocolable::Base < ActiveRecord::Base set_table_name 'protocol' #All attributes of Protocol should be read-only attr_readonly :created_at, :affected_object_type, :affected_object_id, :action_type, :internal_user_id, :system_user_login, :is_console_action attr_accessible :affected_object_type, :affected_object_id, :action_type, :internal_user_id def after_initialize return unless new_record? self.is_console_action = self.called_from_console? self.system_user_login = self.get_system_user_login end protected def called_from_console? (defined? IRB) ? true : false end def get_system_user_login Sys::Admin.get_login end end
class PostsController < ApplicationController before_filter :require_session before_filter :load_and_authorize_user, only: [:new, :create] before_filter :load_and_authorize_post, only: [:edit, :update] params_for :post, :body, :title def new @post = @user.received_posts.build respond_to do |format| format.html format.json { render json: @post } end end def create @post = @user.received_posts.build(post_params) @post.sender_id = @current_user.id respond_to do |format| if @post.save format.html { redirect_to new_post_attached_file_url(@post) } format.json { render json: @post, status: :created } else format.html { render action: 'new' } format.json { render json: @post.errors, status: :unprocessable_entity } end end end def edit end def update respond_to do |format| if @post.update_attributes(post_params) format.html { redirect_to edit_post_attached_file_url(@post, '1'), notice: 'La consulta se ha actualizado' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @post.errors, status: :unprocessable_entity } end end end def show @post = Post.find(params[:id]) authorize! :read, @post end def print @post = Post.find(params[:id]) authorize! :read, @post render layout: 'print' end def destroy @post = Post.find(params[:id]) authorize! :destroy, @post @post.destroy respond_to do |format| format.html { redirect_to profile_url(@post.receiver), notice: 'La consulta se ha eliminado' } format.json { head :no_content } end end protected def load_and_authorize_post @post = Post.find(params[:id]) authorize! :update, @post end def load_and_authorize_user @user = User.find(params[:user_id]) authorize! :post, @user end end
### # Compass ### # Susy grids in Compass require 'susy' require 'modular-scale' require 'animate' # Change Compass configuration # compass_config do |config| # config.output_style = :compact # end # Live reload activate :livereload # Bloggin' activate :blog do |blog| blog.prefix = "blog" blog.layout = "layouts/blog" blog.paginate = true blog.permalink = ":title.html" blog.tag_template = "tag.html" blog.calendar_template = "calendar.html" # blog.permalink = "{category}/{year}/{month}/{day}/{title}.html" # blog.summary_separator = READMORE end # Nice urls activate :directory_indexes # Code highlighting activate :syntax # Change the CSS directory set :css_dir, "css" # Change the JS directory set :js_dir, "js" # Change the images directory set :images_dir, "img" # Change the fonts directory set :fonts_dir, "fonts" set :markdown_engine, :redcarpet set :markdown, :fenced_code_blocks => true, :smartypants => true # Build-specific configuration configure :build do # Requires middleman-favicon-maker # activate :favicon_maker, # :favicon_maker_base_image => "favicon_base.svg" # For example, change the Compass output style for deployment activate :minify_css # Minify Javascript on build activate :minify_javascript # Enable cache buster activate :cache_buster # Use relative URLs # activate :relative_assets # Compress PNGs after build # First: gem install middleman-smusher require "middleman-smusher" activate :smusher # Or use a different image path # set :http_path, "/Content/images/" end
require_relative "../../aws_refresher_spec_common" require_relative "../../aws_refresher_spec_counts" describe ManageIQ::Providers::Amazon::CloudManager::Refresher do include AwsRefresherSpecCommon include AwsRefresherSpecCounts it ".ems_type" do expect(described_class.ems_type).to eq(:ec2) end AwsRefresherSpecCommon::ALL_GRAPH_REFRESH_SETTINGS.each do |settings| context "with settings #{settings}" do before(:each) do stub_refresh_settings(settings) create_tag_mapping @ems = FactoryBot.create(:ems_amazon_with_vcr_authentication) end it "will perform a full refresh" do 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + '_inventory_object') do EmsRefresh.refresh(@ems) EmsRefresh.refresh(@ems.network_manager) EmsRefresh.refresh(@ems.ebs_storage_manager) @ems.reload assert_counts(table_counts_from_api) end assert_common assert_mapped_tags_on_template end end end end it 'pickups existing Vm and MiqTemplate records on Amazon EMS re-adding' do ems = new_amazon_ems VCR.use_cassette(described_class.name.underscore + '_vm_reconnect') do expect { EmsRefresh.refresh(ems) }.to change { VmOrTemplate.count }.from(0) end expect { ems.destroy }.to_not change { VmOrTemplate.count } aggregate_failures do expect(Vm.count).to_not be_zero expect(MiqTemplate.count).to_not be_zero expect(ExtManagementSystem.count).to be_zero end ems = new_amazon_ems VCR.use_cassette(described_class.name.underscore + '_vm_reconnect') do expect { EmsRefresh.refresh(ems) } .to change { VmOrTemplate.distinct.pluck(:ems_id) }.from([nil]).to([ems.id]) .and change { VmOrTemplate.count }.by(0) .and change { MiqTemplate.count }.by(0) .and change { Vm.count }.by(0) end end def new_amazon_ems FactoryBot.create(:ems_amazon_with_vcr_authentication, :provider_region => 'eu-central-1') end end
require 'addressable/uri' module Addressable # # Add the #scrubbed and #revhost calls # class URI # # These are illegal but *are* found in URLs. We're going to let them through. # Note that ' ' space is one of the tolerated miscreants. # URL_ILLEGAL_BUT_WHATEVER_DOOD_CHARS = '\{\}\| \^\`' # # These are all the characters that belong in a URL # PERMISSIVE_SCRUB_CHARS = URL_ILLEGAL_BUT_WHATEVER_DOOD_CHARS + Addressable::URI::CharacterClasses::UNRESERVED + Addressable::URI::CharacterClasses::RESERVED + '%' # # Replace all url-insane characters by their %encoding. We don't really # care here whether the URLs do anything: we just want to remove stuff that # absosmurfly don't belong. # # This code is stolen from Addressable::URI, which unfortunately has a bug # in exactly this method (fixed here). (http://addressable.rubyforge.org) # Note that we are /not/ re-encoding characters like '%' -- it's assumed # that the url is encoded, but perhaps poorly. # # In practice the illegal characters most often seen are those in # RE_URL_ILLEGAL_BUT_WHATEVER_DOOD_CHARS plus # <>"\t\\ # def self.scrub_url url return url if url.blank? url.gsub(/[^#{PERMISSIVE_SCRUB_CHARS}]+/) do |sequence| sequence.unpack('C*').map{ |c| ("%%%02x"%c).upcase }.join("") end end # # +revhost+ # the dot-reversed host: # foo.company.com => com.company.foo # def revhost return host unless host =~ /\./ host.split('.').reverse.join('.') end # # The md5hash of this URI # # make sure to require 'digest/md5' somewhere... def md5hash Digest::MD5.hexdigest(self.normalize.to_s) end # # +uuid+ -- RFC-4122 ver.5 uuid; guaranteed to be universally unique # # See http://www.faqs.org/rfcs/rfc4122.html # # You ned to require "monkeyshines/utils/uuid" as well... # def url_uuid UUID.sha1_create(UUID_URL_NAMESPACE, self.normalize.to_s) end end end
## Arith Geo # Have the function ArithGeoII(arr) take the array of numbers stored in # arr and return the string "Arithmetic" if the sequence follows an # arithmetic pattern or return "Geometric" if it follows a geometric # pattern. If the sequence doesn't follow either pattern return -1. An # arithmetic sequence is one where the difference between each of the # numbers is consistent, where as in a geometric sequence, each term after # the first is multiplied by some constant or common ratio. Arithmetic # example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54]. Negative # numbers may be entered as parameters, 0 will not be entered, and no array # will contain all the same elements. def ArithGeo2(arr) geo_check(arr) ? "Geometric" : arith_check(arr) ? "Arithmetic" : -1 end def geo_check(arr) geo = true check = arr[1] / arr[0] arr.each_with_index do |_num, i| unless i == arr.length - 1 geo = false unless arr[i + 1] / arr[i] == check end end geo end def arith_check(arr) arith = true check = arr[1] - arr[0] arr.each_with_index do |_num, i| unless i == arr.length - 1 arith = false unless arr[i + 1] - arr[i] == check end end arith end
require 'minitest' require 'minitest/autorun' require 'delve/game' class GameTest < Minitest::Test def setup @display = mock('object') @input = mock('object') @screen_manager = mock('object') @game = Game.new @display, @screen_manager, @input end def test_fail_if_display_is_nil assert_raises RuntimeError do @game = Game.new nil, @screen_manager, @input end end def test_fail_if_screen_manager_is_nil assert_raises RuntimeError do @game = Game.new @display, nil, @input end end def test_fail_if_input_is_nil assert_raises RuntimeError do @game = Game.new @display, @screen_manager, nil end end def test_cannot_start_when_screen_manager_is_empty @screen_manager.expects(:empty?).returns(true) assert_raises RuntimeError do @game.start end end def test_start_game @display.expects(:render) @screen_manager.expects(:empty?).returns(false) @screen_manager.expects(:render).with(@display) @screen_manager.expects(:update).with(@input).returns(true) @game.start end end
require 'httparty' module Jus class AuthenticationService BASE_URL = "https://api.revistajus.com.br/1.0/auth" Result = Struct.new(:success?, :error, :value) def initialize @email = "teste@teste.com.br" @password = "Jp@1234" end def call make_request! end private def format_params { "session[email]": @email, "session[password]": @password } end def make_request! begin p result = HTTParty.post(BASE_URL, body: format_params) if result["status"] == "error" Result.new(false, result["message"], nil) else Result.new(true, nil, result) end rescue StandardError => e Result.new(false, e.message, nil) end end end end
class Event < ApplicationRecord # scope :active, -> { where('end_date >= :twelve_hours_ago', twelve_hours_ago: Time.now - 12.hours) } has_many :company_lead_rsvps has_many :trainer_lead_rsvps has_many :company_leads, through: :company_lead_rsvps has_many :trainer_leads, through: :trainer_lead_rsvps has_many :company_lead_rsvp_tickets, through: :company_lead_rsvps has_many :trainer_lead_rsvp_tickets, through: :company_lead_rsvps after_update :check_to_send_emails def check_to_send_emails if self.emails_sent == true return self else self.filter_emails_attendee_or_absentee end end def filter_emails_attendee_or_absentee if self.twelve_hours_later == true byebug company_attendees = self.company_lead_rsvps.where(checked_in: true) trainer_attendees = self.trainer_lead_rsvps.where(checked_in: true) company_absentees = self.company_lead_rsvps.where(checked_in: false) trainer_absentees = self.trainer_lead_rsvps.where(checked_in: false) #COMPANY ATTENDEES if company_attendees.length > 0 company_attendees.map do |company_attendee| attendent_comp_lead = company_attendee.company_lead # Tell the CompanyLeadRsvpTicketMailer to send an email after save containing the ticket ThankYouMailer.with(attendent_comp_lead: attendent_comp_lead).thank_you(attendent_comp_lead).deliver_now end end #TRAINER ATTENDEES if trainer_attendees.length > 0 trainer_attendees.map do |trainer_attendee| attendent_train_lead = trainer_attendee.trainer_lead # Tell the CompanyLeadRsvpTicketMailer to send an email after save containing the ticket ThankYouMailer.with(attendent_train_lead: attendent_train_lead).thank_you(attendent_train_lead).deliver_now end end #COMPANY ABSENTEES if company_absentees.length > 0 company_absentees.map do |company_absentee| absent_comp_lead = company_absentee.company_lead # Tell the CompanyLeadRsvpTicketMailer to send an email after save containing the ticket SorryMailer.with(absent_comp_lead: absent_comp_lead).sorry(absent_comp_lead).deliver_now end end #TRAINER ABSENTEES if trainer_absentees.length > 0 trainer_absentees.map do |trainer_absentee| absent_train_lead = trainer_absentee.trainer_lead # Tell the CompanyLeadRsvpTicketMailer to send an email after save containing the ticket SorryMailer.with(absent_train_lead: absent_train_lead).sorry(absent_train_lead).deliver_now end end self.update(emails_sent: true) else byebug return self end end end
class ChangeAnswersBodyStringToText < ActiveRecord::Migration[5.2] def up change_column :answers, :body, :text end def down # string must be < 255 characters change_column :answers, :body, :string end end
class Book # write your code here def title=(title) @title = titleize(title) end def title @title end def titleize text list = text.capitalize.split(' ') littlewords = ['and', 'the', 'in', 'over', 'of', 'a', 'an'] list.each_with_index do |item, index| if !littlewords.include?(item.downcase) list[index].capitalize! end end return list.join(' ') end end
class CreateProjectBalances < ActiveRecord::Migration def change create_table :project_balances do |t| t.references :project t.date :movement_date t.decimal :amount, :precision => 10, :scale => 2 t.text :notes t.references :user t.timestamps end end end
require 'spec_helper' describe GroupInvitation do let(:group_invitation) { FactoryGirl.create(:group_invitation) } describe "validation" do it "should validate email address" do group_invitation.emails = ' abc@example.com , bbc@example.com ' group_invitation.should have(0).error_on(:emails) group_invitation.emails = 'abc@example.com,' group_invitation.should have(0).error_on(:emails) group_invitation.emails = 'abc@exmapl.com,asdfasdfd' group_invitation.should have(1).error_on(:emails) group_invitation.emails = 'asdfa, example@exmple.com' group_invitation.should have(1).error_on(:emails) group_invitation.emails = 'asdfa, asdf' group_invitation.should have(2).error_on(:emails) end it "should create invitation on create" do invitations = group_invitation.invitations.all invitations.should have(2).items invitations.first.email.should == 'test1@example.com' invitations.second.email.should == 'test2@example.com' invitations.first.message.should == 'some message' invitations.second.message.should == 'some message' end end end
# == Schema Information # # Table name: images # # id :integer not null, primary key # name :string default("") # description :string default("") # taken_at :datetime # created_at :datetime # updated_at :datetime # gallery_id :integer # image_file_id :string # FactoryGirl.define do factory :image do name "test" description "some test image" image_file_id "asdfasdfasdf" end end
class AddAvailableToPackages < ActiveRecord::Migration[6.0] def change add_column :packages, :available, :boolean end end
input_lines = File.new('day-10-input.txt').readlines def parse_line(line) regex = /position=<([\-|\s]\d+), ([\-|\s]\d+)> velocity=<([\-|\s]\d+), ([\-|\s]\d+)>/ matches = regex.match(line).captures { :x => matches[0].strip.to_i, :y => matches[1].strip.to_i, :v_x => matches[2].strip.to_i, :v_y => matches[3].strip.to_i, } end def state(t, points) points.map {|p| [p[:x] + p[:v_x] * t, p[:y] + p[:v_y] * t]} end def display(coords) (0...250).each do |y| puts (0...250).map {|x| coords.include?([x, y]) ? '#' : '.' }.join('') end end points = input_lines.map {|line| parse_line(line)} # assumption: we need to wait until all points are non-negative t_for_positive_coords = (0..20_000).select {|t| state(t,points).flatten.all? {|val| val >= 0}} t_for_positive_coords.each do |t| puts "\n", t, "\n" display(state(t, points)) end
class Station attr_accessor :name attr_writer :created_stations @@created_stations = [] def initialize(name) @name = name @trains = [] @@created_stations << name end def self.print_all_stations @@created_stations end def arrive(train) @trains << train end def print_trains print @trains end def print_trains_by_type passenger_trains = [] cargo_trains = [] @trains.each do |train| if train.class == PassengerTrain passenger_trains << train elsif train.class == CargoTrain cargo_trains << train else puts "Train #{train.id} has wrong type of #{train.type}." end end puts "Passenger trains on station #{@name} are #{passenger_trains}." puts "Cargo trains on station #{@name} are #{cargo_trains}." end def depature(train) @trains.delete(train) end end
class Heroe < ApplicationRecord belongs_to :publisher belongs_to :user has_many_attached :photos has_many :likes, dependent: :destroy has_many :reviews, dependent: :destroy geocoded_by :address after_validation :geocode, if: :will_save_change_to_address? validates :name, :description, :address, :height, :weight, presence: true validates :name, uniqueness: true def self.list list = [] Heroe.all.each do |heroe| list << heroe.name end return list end end
class CompleteQuery < ActiveRecord::Base belongs_to :query serialize :query_result, Array serialize :variables, Hash def fresh? TimeDifference.between(last_executed, Time.now).in_days < 1 end end
class DeleteStorageZoneFromProducts < ActiveRecord::Migration def change remove_column :products, :storage_zone, :string end end
class Order < ApplicationRecord has_many :order_items, dependent: :destroy belongs_to :customer validates :payment, presence: true validates :freight, presence: true validates :order_status, presence: true validates :total_price, presence: true enum order_status: {入金待ち: 0, 入金確認: 1, 製作中: 2, 発送準備中: 3, 発送済み: 4} def freight freight = 800 end def total_quantity order_items.sum("quantity") end def sub_price order_items.sum("price * 1.1 * quantity").round(0) end end # def total_quantity # quantity = 0 # order_items.each do |i| # quantity += i.quantity # end # return quantitys # end
#好久没有做教学视频了,正好最近工作中用到Ruby,所以就想做一套Ruby的教学视频,分享给大家。 =begin 在这次是视频里,我只是将Ruby最基础的知识介绍给大家,这只是适合于没有接触过Ruby的朋友, 对于已经了解Ruby的朋友来说,这套视频显然是很不够的,这也是我今后准备继续推出Ruby系列 视频的动力,希望得到您的理解和支持。 =end __END__ 好吧,Ruby的入门篇先到这里吧,也许您觉得意犹未尽,那么我今后会陆续推出Ruby再入门系列的视频, 在那里我会更加详细地讲解Ruby的基础语法和相关知识,同时为今后使用Ruby on Rails(RoR)打下 一个良好的基础,期待与您下一个视频中见面,88!
class EventImporter attr_accessor :data def initialize(file) @data = Plist::parse_xml(file) end def import(app_session) app = app_session.app data = @data app_session.class.transaction do data["events"].each do |data| event = app.events.find_or_create_by_name!(data["name"]) event.event_infos.create!({ app_session: app_session, time: data["time"], properties: data["properties"] }) end end end end
require 'test_helper' class ImagesControllerTest < ActionDispatch::IntegrationTest def test_index__images_in_desc_order images = [ { imagelink: 'https://learn.appfolio.com/apm/www/images/apm-logo-v2.png', tag_list: %w[appfolio logo] }, { imagelink: 'https://pbs.twimg.com/profile_images/999418366858149888/zKQCw1Ok_400x400.jpg', tag_list: 'foo' }, # rubocop:disable Metrics/LineLength { imagelink: 'https://microsmallcap.com/wp-content/uploads/sites/2/2018/01/AppFolio-The-Dip-is-a-Buying-Opportunity-.png', tag_list: ['appfolio'] } # rubocop:disable Metrics/LineLength ] Image.create(images.reverse) get images_path assert_response :ok assert_select 'h1', 'Images' assert_select '.js-image-link', 3 assert_select '.js-image-link' do |image_elements| image_elements.each_with_index do |image_element, index| assert_select image_element, 'img[src=?]', images[index][:imagelink] end end end def test_index__tags_with_links images = [ { imagelink: 'https://learn.appfolio.com/apm/www/images/apm-logo-v2.png', tag_list: %w[appfolio logo] }, { imagelink: 'https://pbs.twimg.com/profile_images/999418366858149888/zKQCw1Ok_400x400.jpg', tag_list: 'foo' }, # rubocop:disable Metrics/LineLength { imagelink: 'https://microsmallcap.com/wp-content/uploads/sites/2/2018/01/AppFolio-The-Dip-is-a-Buying-Opportunity-.png', tag_list: ['appfolio'] } # rubocop:disable Metrics/LineLength ] Image.create(images.reverse) get images_path assert_response :ok assert_equal images[0][:tag_list], %w[appfolio logo] assert_equal images[2][:tag_list], ['appfolio'] assert_select 'a[data-method=delete]', 3 end def test_index__delete_succeed image = Image.create(imagelink: 'https://www.appfolio.com/images/html/apm-fb-logo.png', tag_list: %w[appfolio company]) assert_difference 'Image.count', -1 do delete image_path(image.id) end assert_redirected_to images_path assert_equal 'You have successfully deleted the image.', flash[:success] assert_select 'img', 0 end def test_new get new_image_path assert_response :ok assert_select 'input#image_tag_list[name=?]', 'image[tag_list]' end def test_create__valid assert_difference('Image.count', 1) do image_params = { imagelink: 'https://i.vimeocdn.com/portrait/328672_300x300', tag_list: 'foo' } post images_path, params: { image: image_params } end assert_redirected_to image_path(Image.last) end def test_create__invalid_with_tags assert_no_difference('Image.count') do image_params = { imagelink: 'https://i.vimeocdn.com/portrait/328672_300x300' } post images_path, params: { image: image_params } end end def test_create__invalid_with_url assert_no_difference('Image.count') do image_params = { imagelink: 'afdsgasd', tag_list: 'foo' } post images_path, params: { image: image_params } end end def test_show__image_found image_show = Image.create!(imagelink: 'https://images.pexels.com/photos/33053/dog-young-dog-small-dog-maltese.jpg?cs=srgb&dl=animal-dog-maltese-33053.jpg&fm=jpg', tag_list: 'foo') # rubocop:disable Metrics/LineLength get image_path(image_show.id) assert_response :ok assert_select '.image-show', count: 1 end def test_show__tag_found image_tag = Image.create!(imagelink: 'https://images.pexels.com/photos/33053/dog-young-dog-small-dog-maltese.jpg?cs=srgb&dl=animal-dog-maltese-33053.jpg&fm=jpg', tag_list: %w[dog adorable]) # rubocop:disable Metrics/LineLength get image_path(image_tag.id) assert_response :ok assert_select 'li', count: 2 end def test_destroy image = Image.create!(imagelink: 'https://www.appfolio.com/images/html/apm-fb-logo.png', tag_list: %w[appfolio company]) assert_difference 'Image.count', -1 do delete image_path(image.id) end assert_redirected_to images_path assert_equal 'You have successfully deleted the image.', flash[:success] end def test_edit image = Image.create!(imagelink: 'https://mydomain/image1.jpg', tag_list: %w[foo bar]) image.save get edit_image_path(image.id) assert_response :ok assert_select '.image-edit', 1 assert_select '.edit_image', 1 end def test_update image = Image.create!(imagelink: 'https://mydomain/image1.jpg', tag_list: %w[foo bar]) put image_path(image.id), params: { image: { tag_list: 'tag' } } assert_redirected_to image_path(image) assert_equal ['tag'], image.reload.tag_list end def test_update__fails_on_empty image = Image.create!(imagelink: 'https://www.image1.com/', tag_list: %w[foo bar]) put image_path image, params: { image: { tag_list: '' } } assert_equal %w[foo bar], image.reload.tag_list assert_select '.alert-alert', 'is an invalid tag list' end end
require 'spec_helper' describe "web/videos/edit" do before(:each) do @web_video = assign(:web_video, stub_model(Web::Video)) end it "renders the edit web_video form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", web_video_path(@web_video), "post" do end end end
require 'rake' $output_files = FileList['*/**/Dockerfile'].pathmap('.build/%X.dimg') def output_files_for(file) $output_files.select { |f| /#{file}/.match(f) } end def output_file_for(file) $output_files.detect { |f| /#{file}/.match(f) } end task default: :all desc 'Builds the base image, BEWARE will love you long time' task base: output_file_for('base/') namespace :services do desc 'Builds all service images' task all: [:base, *output_files_for('services/')] services = FileList['services/*/'].pathmap('%{^services/,}X').pathmap('%{/$,}X') services.each do |svc| desc "Builds an image for #{svc}" task svc.to_sym => [:base, output_file_for("services/#{svc}")] end end namespace :development do desc 'Builds an image for express development' task express: [:base, output_file_for('development/express')] desc 'Builds a base image for rails development' task rails_base: [:base, output_file_for('development/rails_base')] desc 'Builds an image for rails development that includes PostgreSQL' task rails: [:base, :rails_base, output_file_for('development/rails')] desc 'Builds an image for rails development that includes MySQL' task rails_mysql: [:base, :rails_base, output_file_for('development/rails_mysql')] desc 'Builds all development images' task all: [:express, :rails, :rails_mysql] end desc 'Builds all images in dependency order.' task all: [:base, 'services:all', 'development:all'] def image_name(src_file) dirs = src_file.pathmap('%d').split('/') name = dirs[0] if dirs[0] == 'development' name = dirs[-1] elsif dirs[0] == 'services' name = "#{dirs[-2]}:#{dirs[-1]}" end name end def build_image(name, src_dir, out_dir) sh "docker build -t erickbrower/#{name} #{src_dir} && touch #{out_dir}/Dockerfile.dimg" end def source_files_for(file) FileList[file.pathmap('%{^\.build/,}d/**/*')] end rule '.dimg' => ->(f) { source_files_for(f) } do |t| out_dir = t.name.pathmap '%d' mkdir_p out_dir build_image image_name(t.source), t.source.pathmap('%d'), out_dir end
class ContactsController < ApplicationController #before_filter :redirect_member! before_filter :authenticate_user! def activation @contact = Contact.find(params[:id]) @contact.update_attribute(:is_active, false) if params[:deactivate].present? @contact.update_attribute(:is_active, true) if params[:activate].present? @class = @contact.is_active ? "btn" : "btn disabled" redirect_to :back end def search respond_to do |format| format.html end end # GET /contacts # GET /contacts.json def index session[:ppage] = (params[:per_page].to_i rescue 25) if (params[:per_page] && (not params[:per_page.blank?] ) ) @per_page = session[:ppage].to_s params[:ppage] = session[:ppage] if params[:member_query].present? @contacts = Contact.where("first_name LIKE ? OR last_name LIKE ? OR company LIKE ?", "%#{params[:member_query]}%", "%#{params[:member_query]}%", "%#{params[:member_query]}%") elsif params[:tag] @contacts = Contact.search(params).tagged_with(params[:tag]).page(params[:page]).per(session[:ppage]) else @contacts = Contact.search(params) end params.delete :ppage params.delete :per_page @q = params[:query].present? respond_to do |format| format.html # index.html.erb format.json { render json: @contacts.map{ |c| {id: c.id, text: c.to_label} } } # format.json { render json: @contacts.map{ |c| {id: c.id, text: {company: c.company, first_name: c.first_name, last_name: c.last_name } } } } end end def more_contacts id = params[:id].to_i rescue 0 5.times do break if Contact.find_by_id(id) id -= 1 end unless id.nil? @contacts = (id.nil? ? nil : Contact.find_all_by_id(id-10..id).reverse) respond_to do |format| format.js { render partial: "more_contacts" } end unless @contacts.nil? end def tag_cloud if params[:tag] #@contacts = Contact.tagged_with(params[:tag]).page(params[:page]).per_page(50) @contacts = Contact.tagged_with(params[:tag]).page(params[:page]).per(session[:ppage]) @tag = params[:tag] end respond_to do |format| format.html end end def statistics @last_ten = Contact.last(10).reverse @contacts_by_countries = Contact.group(:country).count.sort_by{|k,v| v}.map{|name, val| {label: name, value: val} if val > 10}.compact respond_to do |format| format.html end end # GET /contacts/1 # GET /contacts/1.json def show @contact = Contact.find(params[:id]) @contact.update_attribute(:is_active, false) if params[:deactivate].present? @contact.update_attribute(:is_active, true) if params[:activate].present? @class = @contact.is_active ? "btn" : "btn disabled" @next_contact = @contact.next_company @previous_contact = @contact.previous @members = @contact.members respond_to do |format| format.html # show.html.erb format.json { render json: @contact } end end # GET /contacts/new # GET /contacts/new.json def new if params[:member].present? && params[:member].respond_to?(:to_i) # prefill new form with member's data if @member = Member.find(params[:member]) @contact = Contact.new( company: @member.company, country: @member.country, address: @member.address, city: @member.city, postal_code: @member.postal_code, is_ceres_member: true, ) tag_list = @member.activity_list + @member.brand_list tag_list << "member" @contact.tag_list = tag_list.join(',') end end @contact ||= Contact.new @contact.emails.new respond_to do |format| format.html # new.html.erb format.json { render json: @contact } format.js { render template: 'contacts/new' } end # { render partial: "new" } end # GET /contacts/1/edit def duplicate @contact = Contact.find(params[:id]).duplicate @contact.emails.new render "edit" end # GET /contacts/1/edit def edit @contact = Contact.find(params[:id]) @count = 0 end # POST /contacts # POST /contacts.json def create flash.clear begin @contact = Contact.new(params[:contact]) @contact.update_attribute(:user_id, current_user.id) rescue ActiveRecord::RecordNotUnique => e if e.message =~ /for key 'index_emails_on_address'/ email = e.message.scan(/Duplicate entry '(.*)' for key 'index_emails_on_address'.*/).flatten.first err = ["the email address <strong>'#{email.html_safe}'</strong>", "Check the emails fields"] else company = params[:contact][:company] || "ERROR" country = params[:contact][:country] || "ERROR" err = ["the company <strong>\"#{company.html_safe}\"</strong> in the country: <strong>\"#{country.html_safe}\"</strong>", "Check the company, country, address and first name fields"] end flash[:error] = <<EOL <h3>An error prevented the reccord from being saved (duplicate entry):</h3> Sorry, #{err.first.html_safe} already exists in the database. Please take one of the following action: <ul> <li>#{err.last.html_safe}</li> <li>Do not create the contact, but find and update the already existing company using the search form on the main contact page</li> </ul> EOL #flash[:error] += e.message end respond_to do |format| if @contact.save format.html { redirect_to contacts_path, notice: 'Contact was successfully created.' } format.json { render json: @contact, status: :created, location: @contact } format.js { render template: 'contacts/ajax_new_contact_success' } else @email_error = "error" if @contact.errors.full_messages.map{|m| m if(m =~ /email/i)}.size > 0 format.html { render action: "new" } format.json { render json: @contact.errors, status: :unprocessable_entity } format.js { render template: 'contacts/_form' } #format.js { render template: 'contacts/new' } end end end # PUT /contacts/1 # PUT /contacts/1.json def update flash.clear begin @contact = Contact.find(params[:id]) @contact.update_attribute(:updated_by, current_user.id) rescue ActiveRecord::RecordNotUnique => e if e.message =~ /for key 'index_emails_on_address'/ email = e.message.scan(/Duplicate entry '(.*)' for key 'index_emails_on_address'.*/).flatten.first err = ["the email address <strong>'#{h(email)}'</strong>", "Check the emails fields"] else company = params[:contact][:company] || "ERROR" country = params[:contact][:country] || "ERROR" err = ["the company <strong>\"#{h(company)}\"</strong> in the country: <strong>\"#{h(country)}\"</strong>", "Check the company, country, address and first name fields"] end flash[:error] = <<EOL <h3>An error prevented the reccord from being saved (duplicate entry):</h3> Sorry, #{h(err.first)} already exists in the database. Please take one of the following action: <ul> <li>#{h(err.last)}</li> <li>Do not create the contact, but find and update the already existing company using the search form on the main contact page</li> </ul> EOL end respond_to do |format| if @contact.update_attributes(params[:contact]) format.html { redirect_to @contact, notice: 'Contact was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @contact.errors, status: :unprocessable_entity } end end end # DELETE /contacts/1 # DELETE /contacts/1.json def destroy @contact = Contact.find(params[:id]) @contact.destroy #@contact.version respond_to do |format| format.html { redirect_to contacts_url } format.json { head :no_content } end end end
class CreateInterests < ActiveRecord::Migration def self.up create_table :interests do |t| t.column :name, :string, :limit => 255 t.column :status, :enum, :limit => [:active, :suspended, :deleted], :default => :active t.column :parent_id, :integer, :default => nil t.column :position, :integer t.column :source_id, :integer, :default => 1 t.column :cobrand_id, :integer, :default => nil end add_index :interests, :name add_index :interests, :status add_index :interests, :cobrand_id add_index :interests, :parent_id end def self.down drop_table :interests end end
module Paperclip # Paperclip processors allow you to modify attached files when they are # attached in any way you are able. Paperclip itself uses command-line # programs for its included Thumbnail processor, but custom processors # are not required to follow suit. # # Processors are required to be defined inside the Paperclip module and # are also required to be a subclass of Paperclip::Processor. There is # only one method you *must* implement to properly be a subclass: # #make, but #initialize may also be of use. #initialize accepts 3 # arguments: the file that will be operated on (which is an instance of # File), a hash of options that were defined in has_attached_file's # style hash, and the Paperclip::Attachment itself. These are set as # instance variables that can be used within `#make`. # # #make must return an instance of File (Tempfile is acceptable) which # contains the results of the processing. # # See Paperclip.run for more information about using command-line # utilities from within Processors. class Processor attr_accessor :file, :options, :attachment def initialize(file, options = {}, attachment = nil) @file = file @options = options @attachment = attachment end def make; end def self.make(file, options = {}, attachment = nil) new(file, options, attachment).make end # The convert method runs the convert binary with the provided arguments. # See Paperclip.run for the available options. def convert(arguments = "", local_options = {}) Paperclip.run( Paperclip.options[:is_windows] ? "magick convert" : "convert", arguments, local_options ) end # The identify method runs the identify binary with the provided arguments. # See Paperclip.run for the available options. def identify(arguments = "", local_options = {}) Paperclip.run( Paperclip.options[:is_windows] ? "magick identify" : "identify", arguments, local_options ) end end end
#!/usr/bin/ruby require 'csv' require 'bundler' Bundler.require input_file_name = ARGV[0] || "lat_long.csv" output_file_name = ARGV[1] || "lat_long_reverse_coded.csv" header = "place_id|line4| line3| line2| line1| offsetlat| county| house| offsetlon| countrycode| postal| longitude| state| street| country| latitude| cross| radius| quality| city| neighborhood" File.open(output_file_name, 'w') { |f| f.write("#{header}\n") } count = %x{wc -l #{input_file_name}}.split.first.to_i puts "starting reverse geo-coding process for #{count} places\n" pbar = ProgressBar.create(:format => '%c/%C %a |%b>>%i| %p%% %t', :starting_at => 0, :total => count, :title => "Places", :smoothing => 0.6) CSV.foreach(input_file_name) do |row| latitude = row[0] longitude = row[1] place_id = row[2] response = Faraday.get "http://where.yahooapis.com/geocode?q=#{latitude},#{longitude}&gflags=AR&flags=J&appid=#{ENV['app_id']}" begin json_response = JSON.parse(response.body)["ResultSet"] rescue p "error" next end pbar.increment if json_response["Found"].to_i > 0 result = json_response["Results"].first csv ="#{place_id}|#{result['line4']}| #{result['line3']}| #{result['line2']}| #{result['line1']}| #{result['offsetlat']}| #{result['county']}| #{result['house']}| #{result['offsetlon']}| #{result['countrycode']}| #{result['postal']}| #{result['longitude']}| #{result['state']}| #{result['street']}| #{result['country']}| #{result['latitude']}| #{result['cross']}| #{result['radius']}| #{result['quality']}| #{result['city']}| #{result['neighborhood']}" File.open(output_file_name, 'a') { |f| f.write("#{csv}\n") } else puts "#{json_response.merge( {:latitude => latitude, :longitude => longitude})}\n" end sleep(7) end
Rails.application.routes.draw do resources :users do resources :contacts end resources :pitches end
class AddDeviceMobileToTemple < ActiveRecord::Migration def change add_column :temples, :device_no, :string end end
require "C:/Users/oscar/.RubyMine2018.2/config/scratches/scratch_1.rb" class CarModel < CarMaker attr_accessor :milage, :type, :transmission, :stockNumber, :drivetrain, :status, :fuelEconomy, :maker, :model, :year, :trim, :features @milage @type @transmission @stockNumber @drivetrain @status @fuelEconomy @maker @model @year @trim @features def initialize(milage, type, transmission, stockNumber, drivetrain, status, fuelEconomy, maker, model, year, trim, features) super(maker) @milage = milage @type = type @transmission = transmission @stockNumber = stockNumber @drivetrain = drivetrain @status = status @fuelEconomy = fuelEconomy @model = model @year = year @trim = trim @features = features @maker = maker end def to_s return "#@maker, #@model, #@trim, #@milage, #@year, #@type, #@drivetrain, #@transmission, #@stockNumber, #@status, #@fuelEconomy, #@features" end end
class User #attr_accessible :name, :password, :email attr_accessor :password include Mongoid::Document include Mongoid::Timestamps field :name, :type => String field :email, :type => String field :password_hash, type: String field :password_salt, type: String field :pin, type: String embeds_many :metadata embeds_many :id_references before_save :encrypt def self.create_it(params) user = self.new.create_me(params[:user]) user end def self.authenticate(name: nil, password: nil, pin: nil) if pin user = self.where(pin: pin).first valid = user if user else user = self.where(name: name).first valid = user if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) end valid ? valid : nil end #{"event":"kiwi_identity", # "ref":[{"link":"http://localhost:3021/api/v1/parties/545964134d6174bb8d050000","ref":"party"}, # {"ref":"sub","id":"545963db4d61745aead30000"}], # "id_token":{"sub":"545963db4d61745aead30000"}} def self.id_reference(event) user = self.find(event["id_token"]["sub"]) user.add_references(refs: event["ref"]) end def create_me(params) self.name = params[:name] self.password = params[:password] self.email = params[:email] self.save self end def update_meta(meta: nil) meta.each do |name, value| mt = self.metadata.where(name: name).first if mt mt.update_it(name: name, value: value) else self.metadata << Metadatum.create_it(name: name, value: value) end end save end def update_it(params) self.attributes = (params[:user]) if params[:employee].present? emp = Employee.find(params[:employee]) self.employee = emp end save end def encrypt if password.present? self.password_salt = BCrypt::Engine.generate_salt self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) end end def add_references(refs: nil) refs.each do |ref| if ref["ref"] != "sub" id_ref = self.id_references.where(ref: ref["ref"]).first if id_ref id_ref.update_it(ref: ref["ref"], link: ref["link"], id: ref["id"]) else self.id_references << IdReference.create_it(ref: ref["ref"], link: ref["link"], id: ref["id"]) end end end self.save end def reference_for(ref: nil) ref = self.id_references.where(ref: ref).first ref ? ref : IdReference.new end end
require 'uri' module UrlValidation extend ActiveSupport::Concern # Test for valid URL - defaults back to system urls in invalid. def validate_url(url_param) if url_param uri = URI.parse(url_param) scheme = uri.scheme if uri # Must be a http or https scheme, don't accept ftp, file, mailto etc. if scheme && %w[http https].include?(scheme) return url_param end end nil # do nothing but don't kill the request end end
class ApplicationController < ActionController::Base protect_from_forgery # Check layout on user type layout :per_user_layout protected # Use layout depending on user type def per_user_layout if current_user.is_a? Admin 'admin' elsif current_user.is_a? Student 'student' elsif current_user.is_a? Technician 'technician' elsif current_user.is_a? Teacher 'teacher' else #Not signed in 'application' end end end
class BulletinBoardCommentsController < BaseController before_filter :find_bulletin_board before_filter :find_bulletin_board_comment, only: [:edit, :update, :destroy] def index @bulletin_board_comments = @bulletin_board.bulletin_board_comments.includes(:user).order("id DESC").page(params[:page]).per(50) end def new @bulletin_board_comment = @bulletin_board.bulletin_board_comments.new end def create @bulletin_board.bulletin_board_comments.create(params[:bulletin_board_comment]) redirect_to bulletin_board_bulletin_board_comments_url(bulletin_board_id: @bulletin_board.id) end def edit @bulletin_board_comment = @bulletin_board.bulletin_board_comments.where(id: params[:id]).first end def update @bulletin_board_comment.update_attributes!(params[:bulletin_board_comment]) redirect_to bulletin_board_bulletin_board_comments_url(bulletin_board_id: @bulletin_board.id) end def destroy @bulletin_board_comment.destroy redirect_to bulletin_board_bulletin_board_comments_url(bulletin_board_id: @bulletin_board.id) end private def find_bulletin_board @bulletin_board = BulletinBoard.where(id: params[:bulletin_board_id]).first end def find_bulletin_board_comment @bulletin_board_comment = BulletinBoardComment.where(id: params[:id]).first end end
class AddDefaultFiltersToEasySetting < ActiveRecord::Migration def self.up EasySetting.create(:name => 'easy_budget_sheet_query_default_filters', :value => {'spent_on' => {:operator => 'date_period_1', :values => {:from => '', :period => 'last_month', :to => ''}}}) end def self.down end end
require 'rails_helper' RSpec.describe TracesServices::DistanceUpdater, type: :service do describe '#call' do subject { described_class.new(trace).call } let(:trace) { Trace.create(coordinates: coordinates) } let(:coordinates) do [{"latitude": 32.9378204345703, "longitude": -117.230239868164}, {"latitude": 32.9378318786621, "longitude": -117.230209350586}, {"latitude": 32.9378814697266, "longitude": -117.230102539062}].to_json end let(:expected_coordinates_with_distances) do [{"latitude": 32.9378204345703, "longitude": -117.230239868164, "distance": 0}, {"latitude": 32.9378318786621, "longitude": -117.230209350586, "distance": 4}, {"latitude": 32.9378814697266, "longitude": -117.230102539062, "distance": 16}].to_json end it 'should calculate all "distances" for each coordinate' do subject expect(trace.coordinates).to eq expected_coordinates_with_distances trace.coordinates_as_hash.each do |coordinate| expect(coordinate.has_key?(:distance)).to be_truthy expect(coordinate[:distance]).not_to be_blank end end end end
Vagrant.configure("2") do |config| # Obtendo máquina virtual centos/7 padrão config.vm.box = "centos/7" # Configura a VM config.vm.provider "virtualbox" do |vb| vb.gui = false vb.memory = "6144" end # script de provisionamento da VM config.vm.provision "shell", inline: <<-SHELL # Se ocorrer qualquer erro o script termina com falha set -e #Repete os comandos executados set -x # Define variaveis que serão usadas nesse script export HOSTNAME=hdp262.dell.local export IP=`ip address | grep eth0$ | awk '{print $2}' | cut -d/ -f1` export AMBARIUSER=ambari export AMBARIPASSWORD=ambari export AMBARIDATABASE=ambari_db export AMBARISCHEMA=ambari_schema export PGPASSWORD=$AMBARIPASSWORD export HIVEUSER=hive export HIVEDATABASE=hive_db export HIVEPASSWORD=hive # Configura o hostname da maquina virtual echo $HOSTNAME > /etc/hostname hostname $HOSTNAME cat > /etc/sysconfig/network <<CFG NETWORKING=yes HOSTNAME=$HOSTNAME CFG # Configura o arquivo de hosts grep -v $HOSTNAME /etc/hosts > /tmp/hosts echo "$IP $HOSTNAME" >> /tmp/hosts cp -f /tmp/hosts /etc/hosts #Cria uma chave SSH para o usuario root para acesso automatico cat /dev/zero | ssh-keygen -q -N "" > /dev/null || /bin/true cat ~/.ssh/id_rsa.pub > ~/.ssh/authorized_keys ssh -oStrictHostKeyChecking=no root@localhost ls ssh -oStrictHostKeyChecking=no root@$HOSTNAME ls #Desabilita o SELinux sed -i 's/^SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config setenforce 0 #Configura limite de numero de arquivos para o usuario cat > /etc/security/limits.conf <<CFG * soft nofile 10000 * hard nofile 10000 CFG ulimit -n 10000 #Copiado do docker, Prepara o sistema para a instalação do system.d (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == systemd-tmpfiles-setup.service ] || rm -f $i; done); rm -f /lib/systemd/system/multi-user.target.wants/*; rm -f /etc/systemd/system/*.wants/*; rm -f /lib/systemd/system/local-fs.target.wants/*; rm -f /lib/systemd/system/sockets.target.wants/*udev*; rm -f /lib/systemd/system/sockets.target.wants/*initctl*; rm -f /lib/systemd/system/basic.target.wants/*; rm -f /lib/systemd/system/anaconda.target.wants/*; #Faz a instalação dos pacotes necessários yum install epel-release -y yum update -y yum install -y scp curl unzip tar wget python27 yum install -y yum-utils yum-plugin-ovl git bind-utils yum install -y openssh-server openssh-clients yum install -y krb5-workstation vim initscripts htop systemd* yum install -y ntp #Instala o utilitario jq (Json Query) curl -o /usr/bin/jq http://stedolan.github.io/jq/download/linux64/jq && chmod +x /usr/bin/jq #Habilita serviços systemctl enable sshd systemctl enable ntpd #Desabilita firewall systemctl disable firewalld service firewalld stop #Instala o banco de dados postgres yum install -y postgresql-server postgresql-contrib postgresql-jdbc* postgresql-setup initdb || /bin/true systemctl enable postgresql #Configura acesso para o banco de dados postgres sed -i "s/#listen_addresses.*/listen_addresses = '*'/g" /var/lib/pgsql/data/postgresql.conf sed -i 's/#port = 5432.*/port = 5432/g' /var/lib/pgsql/data/postgresql.conf sed -i 's|host.*all.*all.*127.0.0.1/32.*ident|host all all 0.0.0.0/0 trust|g' /var/lib/pgsql/data/pg_hba.conf sed -i 's|local.*all.*all.*peer|local all all trust|g' /var/lib/pgsql/data/pg_hba.conf #Inicia o banco de dados postgres systemctl start postgresql #Configura o repositorio do ambari para o yum wget -nv http://public-repo-1.hortonworks.com/ambari/centos6/2.x/updates/2.5.2.0/ambari.repo -O /etc/yum.repos.d/ambari.repo wget -nv http://public-repo-1.hortonworks.com/HDP/centos6/2.x/updates/2.6.2.14/hdp.repo -O /etc/yum.repos.d/hdp.repo yum update -y #Instala o agente do ambari yum install -y ambari-agent sed -i "s/hostname=localhost/hostname=$HOSTNAME/g" /etc/ambari-agent/conf/ambari-agent.ini systemctl restart ambari-agent #Instala o servidor do Ambari yum install -y ambari-server #Configura o schema no banco de dados postgres cat > /tmp/ambari_schema.sql <<SQL CREATE DATABASE $AMBARIDATABASE; CREATE USER $AMBARIUSER WITH PASSWORD '$AMBARIPASSWORD'; GRANT ALL PRIVILEGES ON DATABASE $AMBARIDATABASE TO $AMBARIUSER; \\connect $AMBARIDATABASE; CREATE SCHEMA $AMBARISCHEMA AUTHORIZATION $AMBARIUSER; ALTER SCHEMA $AMBARISCHEMA OWNER TO $AMBARIUSER; ALTER ROLE $AMBARIUSER SET search_path to '$AMBARISCHEMA', 'public'; SQL RETRIES=10 until sudo -u postgres psql -f /tmp/ambari_schema.sql || [ $RETRIES -eq 0 ]; do echo "Waiting for postgres server, $((RETRIES--)) remaining attempts..." sleep 1 done psql -U $AMBARIUSER -d $AMBARIDATABASE -c '\\i /var/lib/ambari-server/resources/Ambari-DDL-Postgres-CREATE.sql;' #Configura o servidor ambari com os parametros de acesso para o banco de dados ambari-server setup -s --database=postgres --databasehost=$HOSTNAME --databaseport=5432 --databasename=$AMBARIDATABASE \ --postgresschema=$AMBARISCHEMA --databaseusername=$AMBARIUSER --databasepassword=$AMBARIPASSWORD #Configura timeout para start do servico do ambari grep server.startup.web.timeout /etc/ambari-server/conf/ambari.properties || echo server.startup.web.timeout=180 >> /etc/ambari-server/conf/ambari.properties #Inicia o serviço do servidor ambari ambari-server start #Verifica o status do serviço do servidor sleep 300 ambari-server status #Configura o banco de dados para o Hive metastore echo "CREATE DATABASE $HIVEDATABASE;" | psql -U postgres echo "CREATE USER $HIVEUSER WITH PASSWORD '$HIVEPASSWORD';" | psql -U postgres echo "GRANT ALL PRIVILEGES ON DATABASE $HIVEDATABASE TO $HIVEUSER;" | psql -U postgres #Configura o driver jdbc postgres para uso pelo Ambari ambari-server setup --jdbc-db=postgres --jdbc-driver=/usr/share/java/postgresql-jdbc.jar > ambari-server.log 2>&1 #Criar e evnia arquivo de versões do HDP tee versiondefinitions.json <<CFG { "VersionDefinition": { "version_url":"http://public-repo-1.hortonworks.com/HDP/centos6/2.x/updates/2.6.2.14/HDP-2.6.2.14-5.xml" } } CFG curl -H "X-Requested-By: ambari" -X POST -u admin:admin http://$HOSTNAME:8080/api/v1/version_definitions -d @versiondefinitions.json #Substitui hostname no arquivo de propriedade do HIVE (Bug do blueprint) sed -i "s/%HOSTGROUP::host_group_1%/$HOSTNAME/g" /vagrant/blueprints/cluster_configuration.json #Envia as configurações de blueprint para o servidor curl -H "X-Requested-By: ambari" -X POST -u admin:admin http://$HOSTNAME:8080/api/v1/blueprints/singlenode -d @/vagrant/blueprints/cluster_configuration.json #Executa o Blueprint tee hostmapping.json <<CFG { "blueprint" : "singlenode", "default_password" : "admin", "repository_version" : "2.6.2.14-5", "host_groups" : [ { "name" : "host_group_1", "hosts" : [ { "fqdn" : "$HOSTNAME" } ] } ] } CFG curl -H "X-Requested-By: ambari" -X POST -u admin:admin http://$HOSTNAME:8080/api/v1/clusters/singlenode -d @hostmapping.json SHELL end
class AddUpdateButtonToParentDetails < ActiveRecord::Migration def change add_column :parent_details, :update_button, :boolean, default: false end end
require_relative 'player' require_relative 'board' require_relative 'battleship' require 'pry' class BattleshipGame attr_reader :player1, :player2, :player, :target def initialize(player1, player2) @player1 = player1 @player2 = player2 @player = player2 @target = player1 end def attack(array, symbol = :X) target.board[array] = symbol player.blankboard[array] = symbol end def count board.count end def game_over? board.won? end def play_turn switch_player system('clear') player.display(target) test_attack(player.get_play) end def switch_player @player, @target = @target, @player end def test_attack(player_input) # binding.pry puts "attacked: #{player_input}" if target.board[player_input] == :n print 'no ships hit' attack(player_input, :O) elsif target.board[player_input] == :O print 'already hit that' test_attack(player.get_play) else print 'hit a ship!' attack(player_input) end end def play fill_boards play_turn until @player.board.won? p "#{player.name} wins!" end def fill_boards p 'How many ships should each player have? ' ships = gets.chomp.to_i [player1, player2].each { |players| players.set_board(ships) } # [player1, player2].each do |players| # if players.class == ComputerPlayer # players.board.populate_grid(ships) # else # players.set_board(ships) # end # end end end if __FILE__ == $PROGRAM_NAME system('clear') puts "Welcome to Battleship!\n\nPlayer1 computer? (yes/no): " if gets.chomp == 'yes' player1 = ComputerPlayer.new('Yessica') else puts "What\'s your name?" player1 = HumanPlayer.new(gets.chomp) end puts 'Player2 computer? (yes/no): ' if gets.chomp == 'yes' player2 = ComputerPlayer.new('Shezebelle') else puts "What\'s your name?" player2 = HumanPlayer.new(gets.chomp) end BattleshipGame.new(player1, player2).play end
require_relative 'subject_not_allowed_error' class Todo include Comparable attr_reader :subject, :state def initialize(subject) raise SubjectNotAllowedError.new("Subject must not contain these characters: <>") if subject.match(/<.*>/m) @subject = subject @state = :open end def close @state = :closed end def open @state = :open end def <=>(other) self.subject <=> other.subject end def to_s "#{@subject} (#{@state})" end end
module TheCityAdmin class UserRole < ApiObject GroupTypes = {:cg => 'CG', :service => 'Service', :campus => 'Campus'} Titles = {:leader => 'Leader', :manager => 'Manager', :volunteer => 'Volunteer', :participant => 'Participant'} tc_attr_accessor :user_id, :active, :created_at, :group_api_url, :group_id, :group_name, :group_type, :id, :last_engaged, :title # Constructor. # # @param json_data (optional) JSON data of the user role. def initialize(json_data = nil) @writer_object = UserRoleWriter initialize_from_json_object(json_data) unless json_data.nil? end end end
class ReceptionistsController < ApplicationController before_action :set_receptionist, only: [:show, :edit, :update, :destroy] def index respond_to do |format| format.html format.json do render json: ReceptionistDatatable.new(params, view_context: view_context) end end end def show; end def new @receptionist = Receptionist.new end def edit; end def create user = User.find(params[:receptionist][:user_id]) @receptionist = Receptionist.new(receptionist_params) respond_to do |format| if @receptionist.save && user.update(user_params) format.html do flash[:notice] = 'El elemento ha sido guardado correctamente.' redirect_to receptionists_path end format.json { render :show, status: :created, location: @receptionist } else format.html do flash[:alert] = 'Ocurrió un error al guardar el elemento. Por favor verifique la información' render :new end format.json { render json: @receptionist.errors, status: :unprocessable_entity } end end end def update user = User.find(params[:receptionist][:user_id]) respond_to do |format| if @receptionist.update(receptionist_params) && user.update(user_params) format.html do flash[:notice] = 'El elemento ha sido guardado correctamente.' redirect_to receptionists_path end format.json { render :show, status: :ok, location: @receptionist } else format.html do flash[:alert] = 'Ocurrió un error al guardar el elemento. Por favor verifique la información' render :edit end format.json { render json: @receptionist.errors, status: :unprocessable_entity } end end end def destroy @receptionist.destroy respond_to do |format| format.html do flash[:notice] = 'El elemento ha sido eliminado correctamente' redirect_to receptionists_url end format.json { head :no_content } end end def _form; end private def set_receptionist @receptionist = Receptionist.find(params[:id]) end def receptionist_params params.require(:receptionist).permit(:user_id, :work_center_id) end def user_params params.require(:user).permit(:first_name, :last_name, :mother_last_name) end end
class PostCommentsController < ApplicationController def create # 先ずはPostテーブルのidを取ってくる post_image = PostImage.find(params[:post_image_id]) #current_user=>サインインしているユーザーを取得する Gem_deviseで使えるようになる Userモデルを参照 フォームからは送られていないのでアクションで記述 #ユーザーidと紐づけてcommentデータを作成。post_comment_paramsはストロングパラメータ。creteにはいつもつけてるね comment = current_user.post_comments.new(post_comment_params) # 上記でユーザーIDを付与したcommentができたけれども # ↑にさらに、post_imageのidを付与する(post_imageは1行目で定義したやつ) comment.post_image_id = post_image.id #User.idとPostImage.idの情報がくっついたcommentのデータができたぞ! comment.save redirect_to post_image_path(post_image) #このアクションの1行目で指定したpost_image => PostImage.find(params[:post_image_id]) end # ストロングパラメータ private def post_comment_params params.require(:post_comment).permit(:user_id, :post_image_id, :comment) end end