text
stringlengths
10
2.61M
class Friendship < ActiveRecord::Base belongs_to :friender, class_name: 'User', optional: true belongs_to :friendee, class_name: 'User', optional: true end
class LanguagesController < ApplicationController before_action :set_language, only: [:show] # GET /languages/1 # GET /languages/1.json def show @snippets = Snippet.where(language: @language, private: false) end # DELETE /languages/1 # DELETE /languages/1.json def destroy @language.destroy respond_to do |format| format.html { redirect_to languages_url, notice: 'Language was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_language @language = Language.find_by(slug: params[:slug]) end end
require 'tsukurepo_backend/services/v1/tsukurepo_services_pb' class TsukurepoGrpcClient class << self attr_reader :host, :port, :authority def configure(host:, port:, authority:) @host = host @port = port @authority = authority end def stub(service) TsukurepoBackend::Services::V1::const_get(service.to_s.camelcase)::Stub.new( "#{self.host}:#{self.port}", :this_channel_is_insecure, channel_args: { 'grpc.default_authority' => self.authority }, ) end end end TsukurepoGrpcClient.configure( authority: Rails.application.config.x.grpc_service[:tsukurepo_backend][:authority], host: Rails.application.config.x.grpc_service[:tsukurepo_backend][:host], port: Rails.application.config.x.grpc_service[:tsukurepo_backend][:port], )
#!/usr/bin/env ruby ### Config: Amazon S3 credentials s3bucket = "mys3bucket" ### Config: temporary directory output_dir = "/path/to/dir" ### Config: default exclude patters for `tar` command excludes = [ ".git", "node_modules" ] ### Config: select directories to backup d = Hash.new d["MySiteName"] = Hash.new d["MySiteName"]["slug"] = "myslug" d["MySiteName"]["directory"] = "/path/to/dir" d["MySiteName"]["excludes"] = [ "myfirstexcludepattern", "mysecondexcludepattern" ] ### END Config ## -------- Don't edit below this line -------- ## # Parse options (eg. "ruby test.rb --period monthly") require 'optparse' require 'yaml' options = {} OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on('-p', '--period PERIOD', 'Period') { |v| options[:period] = v } end.parse! # Preparation puts "Initialising file backup" puts "Checking file backup directory exists..." success = system("mkdir -p #{output_dir}") if(!success) puts ">>>> Error: Problem creating file backup directory <<<<" end # Datestamping datestamp = Time.now day = datestamp.strftime("%d") dayofweek = datestamp.strftime("%A") # If script has period option passed into it, use that if( options[:period] and ( options[:period]=='month' or options[:period]=='week' or options[:period]=='day' ) ) period = options[:period] # Otherwise, automatically figure out the period of backup else if(day=="01") period = "month" elsif(dayofweek=="Sunday") period = "week" else period = "day" end end puts "Selected period: #{period}" # Loop over directories and backup puts "Starting to backup files..." d.each { |key, val| # Create tarball from directory puts "Creating tarball for #{key}..." filename = "#{val["slug"]}--#{datestamp.strftime("%Y.%m.%d-%H.%M.%S")}" command = "tar -zcf" command = command + " #{output_dir}/#{filename}.tar.gz" if(val["excludes"]) excludes = excludes.concat(val["excludes"]).uniq end excludes.each { |excl| command = command + " --exclude='#{excl}'" } command = command + " #{val["directory"]}" success = system(command) if(!success) puts ">>>> Error: Problem creating tarball for #{key}" puts ">>>> filename: #{filename}" next end puts "Finished creating tarball for #{key}" # Remove old S3 backups puts "Removing old backups for #{key} (2 #{period}s ago)..." command = "aws s3 rm --recursive s3://#{s3bucket}/#{val['slug']}_files_previous_#{period}" success = system(command) if(!success) puts ">>>> Error: couldn't remove old backups for #{key} (2 #{period}s ago)" else puts "Old backup removed" end # Move previous backup into previous_ folder puts "Moving existing backup from past #{period} to previous folder..." command = "aws s3 mv --recursive s3://#{s3bucket}/#{val['slug']}_files_#{period} s3://#{s3bucket}/#{val['slug']}_files_previous_#{period}" success = system(command) if(!success) puts ">>>> Error: couldn't move existing backup for #{key} (1 #{period}s ago)" else puts "Previous backup moved" end # Upload new backup puts "Uploading new backup for #{key} (filename: #{filename}.tar.gz)..." command = "aws s3 cp #{output_dir}/#{filename}.tar.gz s3://#{s3bucket}/#{val['slug']}_files_#{period}/#{filename}.tar.gz" success = system(command) if(!success) puts ">>>> Error: couldn't upload new backup for #{key}" else puts "Uploaded new backup for #{key}" end # Remove local dumps puts "Removing local backup file for #{key} (filename: #{filename}.tar.gz)" command = "rm #{output_dir}/#{filename}.tar.gz" success = system(command) if(!success) puts ">>>> Error: couldn't remove local backup file for #{key} (filename: #{filename}.tar.gz)" else puts "Finished removing local backup file #{key} (filename: #{filename}.tar.gz)" end } # Finish puts "Files backup complete."
class AddPointsManallyAssignedToCard < ActiveRecord::Migration def change add_column :cards, :points_manuallly_assigned, :boolean, default: false end end
class Admin::ReadingsController < ApplicationController unloadable # making unloadable per http://dev.rubyonrails.org/ticket/6001 before_filter :authorize_super_admin layout 'admin' helper :device def index today = Date.today thirtyDaysAgo = today - 30 if params if params[:search] if params[:search][:device_id].empty? # selected "All" in the device list. @readings = Reading.paginate(:per_page=>ResultCount, :page => params[:page], :conditions=>["created_at > ?", thirtyDaysAgo.to_s], :order => "created_at desc") else # filter by device @readings = Reading.paginate(:per_page=>ResultCount, :page => params[:page],:conditions => ["device_id = ? and created_at > ? ", params[:search][:device_id], thirtyDaysAgo.to_s], :order => "created_at desc") end else @readings = Reading.paginate(:per_page=>ResultCount, :page => params[:page], :conditions=>["created_at > ?", thirtyDaysAgo.to_s], :order => "created_at desc") end else @readings = Reading.paginate(:per_page=>ResultCount, :page => params[:page], :conditions=>["created_at > ?", thirtyDaysAgo.to_s], :order => "created_at desc") end end end
require 'endeca' require 'thwait' class NavigationController < ApplicationController before_filter :setup_mode, :only => [:index] before_filter :display_category_sub_tabs, :only => [:index, :site_wide_helpful_reviews, :site_wide_recent_reviews] def index expires_in 30.minutes, :public => cache_control_public? if cacheable? # initialize the navigation state @nav_state = NavState.new params @nav_state[:per_page] = cookies['navsize'] # see if we are on a landing page @landing_page = LandingPage.find_by_param params[:lp_id] # , :include => [:browse_dimension_1, :browse_dimension_2] if @landing_page # make sure landing page is active return handle_resource_not_found unless @landing_page.active? # make sure the permalink is canonical...if not then get there! return permanent_redirect_to(params.merge(:lp_id => @landing_page.permalink)) unless @landing_page.permalink == params[:lp_id] # the full N values are the landing page N values plus the N values in the query string n = @landing_page.perma_n unless @nav_state[:N].blank? @extra_n = @nav_state[:N] n += ' ' + @extra_n end @nav_state[:N] = LandingPage.clean_dim_value_ids n @category = @landing_page.category end # check if we should be in a landing page with a different permalink unless @nav_state.search? lp = LandingPage.find_by_dim_value_ids @nav_state[:N] if lp && lp.active? && lp != @landing_page params.delete :N # all the N values can be rolled up behind an :lp_id! return permanent_redirect_to(params.merge(:lp_id => lp.permalink)) end end # if we're in a local cat and the user hasn't done a local search, we need to default # the results to user's location, if possible # Grrrr...I don't like this at all...it means that google and other bots only ever # see Chicago, IL :( We have to fix local at some point! if @category && @category.local? && !@nav_state.local? loc = 'Chicago, IL' if session_user && !session_user.city.blank? && !session_user.state.blank? loc = "#{session_user.city}, #{session_user.state}" elsif session_user && !session_user.zip_code.blank? zip = ZipCode.find_by_zip_code session_user.zip_code loc = zip.city_state_text if zip end logger.debug "Needed to default location to #{loc}" @nav_state[:l] = loc end # oops, couldn't resolve the location, let the user disambiguate it if @nav_state.local? && !@nav_state.resolved_location? return render(:action => 'unresolved', :layout => 'application') end # make sure the query is executable return handle_resource_not_found unless @nav_state.executable? # execute and render the search results return render_search_results if @nav_state.search? # execute and render the recent reviews return render_recent_reviews if recent_reviews_mode? # parallelized query with multiple result sections return render_landing_page_with_modules if @extra_n.blank? && @landing_page && @landing_page.children.count > 0 # normal query and a flat list of results return render_leaf_top_rated_products end def show_all @dim_name = params[:dim_name] @nav_state = NavState.new params @nav_state[:per_page] = 1 @endeca_req = Endeca::Request.new @nav_state.endeca_opts @endeca_res = @endeca_req.execute @alpha_sort = !App.endeca['non_alpha_sorted_dims'].include?(params[:dim_name]) render :update do |page| render_lightbox(page, 'show_all') end end def render_leaf_top_rated_products if @nav_state.local? @nav_state[:sort] = 'distance-0' else @nav_state[:sort] = 'is_sold_on-0' end @nav_state[:tab] = @tab = :top_rated # execute the query to Endeca @endeca_res = Endeca::execute @nav_state.endeca_opts generate_landing_page_param # pagination total_recs = @endeca_res.metainfo.aggregate_total_number_of_matching_records.to_i recs_per_page = @endeca_res.metainfo.number_of_records_per_page.to_i @paginator = Paginator.new self, total_recs, recs_per_page, @nav_state[:page].to_i @offset = @paginator.current.offset # The SEO text for leaf categories still contains "worst rated" links. This section # and supports that by taking the user to the last page of results, attempting to show # a full page size worth of data if (params[:sort] =~ /stars-0/) last_page = @paginator.last.number @offset = total_recs - recs_per_page @offset = 0 if @offset < 0 @endeca_res = Endeca::execute @nav_state.endeca_opts.merge({:Nao => @offset}) total_recs = @endeca_res.metainfo.aggregate_total_number_of_matching_records.to_i recs_per_page = @endeca_res.metainfo.number_of_records_per_page.to_i @paginator = Paginator.new self, total_recs, recs_per_page, last_page end @items = Product.from_endeca_response(@endeca_res) @item_class = Product @show_landing_only_elements = (@paginator.current.number == 1) configure_analytics @meta_nofollow, @meta_noindex = @nav_state.meta_robots @meta_nofollow |= review_it_mode? @meta_noindex |= review_it_mode? load_landing_page_info render :action => 'leaf' end def load_reviews_in_last_n_days(days) @nav_state[:Nu] = nil @nav_state[:record_type] = :reviews @nav_state[:suppress_category_in_query_string] = true @nav_state[:reviews_within_n_days] = days # execute the query to Endeca @endeca_res = Endeca::execute @nav_state.endeca_opts(:delete => [:Nu, :D, :Di, :Dx]) @items = Review.from_endeca_response @endeca_res, :include=>[ :source, {:product=>[:stat, :primary_photo_association]}, {:user=>:primary_photo_association}, :stat, :i_ams ] @item_class = Review track_reviews @items # pagination @paginator = Paginator.new self, @endeca_res.metainfo.total_number_of_matching_records.to_i, @endeca_res.metainfo.number_of_records_per_page.to_i, @nav_state[:page].to_i @offset = @paginator.current.offset end def site_wide_helpful_reviews expires_in 30.minutes, :public => cache_control_public? @show = 'highest_rated_reviews' @nav_state = NavState.new params @nav_state[:per_page] = cookies['navsize'] || 15 @meta_noindex, @meta_nofollow = true, false @nav_state[:sort] = 'review_score-1' page = (params[:page] || 1).to_i load_reviews_in_last_n_days(7) # leave this in for the setting of the session[:last_n_value] configure_analytics("helpful reviews") @web_analytics.page_stack = ['Home','Site Wide Highest Rated Reviews', "Site Wide Highest Rated Reviews Page #{page}"] @web_analytics.page_type = 'Home Page' render :action => 'site_wide_highest_rated_reviews' end def site_wide_recent_reviews expires_in 30.minutes, :public => cache_control_public? @show = 'recent_reviews' @nav_state = NavState.new params @nav_state[:per_page] = cookies['navsize'] || 15 @meta_noindex, @meta_nofollow = true, false @nav_state[:sort] = 'review_published_at-1' page = (params[:page] || 1).to_i load_reviews_in_last_n_days(7) # leave this in for the setting of the session[:last_n_value] configure_analytics("recent reviews") @web_analytics.page_stack = ['Home','Site Wide Most Recent', "Site Wide Most Recent Page #{page}"] @web_analytics.page_type = 'Home Page' render :action => 'site_wide_recent_reviews' end protected def setup_mode @mode = params[:mode] return true if recent_reviews_mode? if cookies[:review_it_mode] == 'true' && !review_it_mode? logger.debug "Redirecting to review_it mode page" if logger.debug? return redirect_to(lp_review_it_url(params.merge(:mode => 'review_it'))) elsif review_it_mode? set_review_it_mode end end def render_search_results @meta_noindex, @meta_nofollow = @nav_state.meta_robots @endeca_res = Endeca::execute @nav_state.endeca_opts @products = Product.from_endeca_response @endeca_res, :include => [:stat, {:partner_products=>:prices}] @left_rail_ad_pixels = 130 * @products.size unless @products.blank? # pagination @paginator = Paginator.new self, @endeca_res.metainfo.aggregate_total_number_of_matching_records.to_i, @endeca_res.metainfo.number_of_records_per_page.to_i, @nav_state[:page].to_i @offset = @paginator.current.offset @web_analytics.page_stack = ['Search', 'Search Results'] @web_analytics.page_type = 'Search Results' @web_analytics.page_name += " Page #{params[:page]}" if params[:page] @web_analytics.keywords = "#{Util.strip_html(params[:q].downcase)}" if params[:N] trans_n = @web_analytics.breadcrumbs_to_text(@endeca_res.breadcrumbs) @web_analytics.facet_nav(trans_n,session[:last_n_value],nil) session[:last_n_value] = trans_n else # no N, clear the session session[:last_n_value] = nil end render :action => "search_results" end def render_recent_reviews @meta_noindex, @meta_nofollow = true, false @nav_state[:tab] = @tab = :recent_reviews @nav_state[:sort] = 'review_published_at-1' @nav_state[:reviews_within_n_days] = 7 # execute the query to Endeca @endeca_res = Endeca::execute @nav_state.endeca_opts(:delete => [:Nu, :D, :Di, :Dx]) @items = Review.from_endeca_response(@endeca_res, :include => [:stat, :user, :product, :source]) @item_class = Review track_reviews @items # pagination @paginator = Paginator.new self, @endeca_res.metainfo.total_number_of_matching_records.to_i, @endeca_res.metainfo.number_of_records_per_page.to_i, @nav_state[:page].to_i @offset = @paginator.current.offset @show_landing_only_elements = @paginator.current.number == 1 configure_analytics("recent reviews") if @category && @category.leaf? && (!@category.faceted? || params[:N]) render :action => 'leaf' else render :action => 'intermediate' end end def generate_landing_page_param return if @endeca_res.breadcrumbs.blank? landing_page_dims = [] @endeca_res.breadcrumbs.each { |crumb| unless crumb.dimension_values.blank? dim_value = crumb.dimension_values.last landing_page_dims << "#{crumb.dimension_name}|#{dim_value.dim_value_name}|#{dim_value.dim_value_id}" end } srt = landing_page_dims.sort { |a, b| if a =~ /\ACategory/ -1 elsif b =~ /\ACategory/ +1 else a <=> b end } @landing_page_param = multi_category_landing_page? ? @landing_page.id : srt.join('||') end def render_landing_page_with_modules @nav_state[:sort] = 'is_sold_on-0' # execute the overall query # HACK: the 'if' portion of this conditional is a hack to allow multiple categories on a landing page. # this is for the viewpoints header change, prior to category adjustments. # remove this after the header trial ends. if multi_category_landing_page? n_vals = @nav_state[:N].split n_vals.each do |n| @nav_state[:N] = n if @endeca_res.blank? @endeca_res = Endeca::execute @nav_state.endeca_opts else other_endeca_res = Endeca::execute @nav_state.endeca_opts @endeca_res.dimension_hash['Category']['dimension_values'].concat(other_endeca_res.dimension_hash['Category']['dimension_values']) @endeca_res.dimension_hash['Category']['dimension_values'].sort! { |x,y| x['dim_value_name'] <=> y['dim_value_name'] } if @endeca_res.dimension_hash['Brand Name'] @endeca_res.dimension_hash['Brand Name']['dimension_values'].concat(other_endeca_res.dimension_hash['Brand Name']['dimension_values']) @endeca_res.dimension_hash['Brand Name']['dimension_values'].sort! { |x,y| y['number_of_records'] <=> x['number_of_records'] } end end end else @endeca_res = Endeca::execute @nav_state.endeca_opts end generate_landing_page_param max_modules = OperatingParamCache.instance.nav_module_count relationships = @landing_page.landing_page_relationships.all :include => :child module_sources = relationships[0..(max_modules-1)] link_sources = relationships[max_modules..-1] || [] @show_landing_only_elements = true @product_modules_hash = Hash.new @product_modules = module_sources @product_links = link_sources load_intermediate_modules(@nav_state[:sort]) configure_analytics @meta_nofollow, @meta_noindex = @nav_state.meta_robots @meta_nofollow |= review_it_mode? @meta_noindex |= review_it_mode? load_landing_page_info @nav_state[:tab] = @tab = :summary render :action => 'intermediate' end def load_browse_dimension_values(dimension, ns) return [] if dimension.blank? nav_state = NavState.new :N => ns[:N], :sort => nil, :Nty => nil nav_state[:Xrc] = "id+#{dimension.endeca_dim_id}+dynrank+enabled+dynorder+default+dyncount+50" endeca_req = Endeca::Request.new nav_state.endeca_opts endeca_res = endeca_req.execute dim = endeca_res.dimension_hash[dimension.name] dim_values = [] dim_values = dim.dimension_values unless dim.blank? dim_values.sort_by { |a| a.dim_value_name } end def load_intermediate_modules(sort=nil) if OperatingParamCache.instance.parallel_nav_module_queries_enabled? load_modules_in_parallel(sort) else load_modules_in_series end end def load_modules_in_parallel(sort=nil) res_hash = Hash.new begin # fire off a thread for each module, adding thread to threads threads = ThreadsWait.new @product_modules.each do |lpr| ns = create_nav_state_for_product_module_source lpr, sort endeca_opts = ns.endeca_opts endeca_opts[:N] = endeca_opts[:N].gsub(/ #{ENDECA_PRIMARY_DIM_ID}\Z/, '') req = Endeca::Request.new(endeca_opts) res_hash[lpr] = t = Thread.new(ns) { |x| Thread.current[:request] = req logger.debug "executing request for thread #{Thread.current}" if logger.debug? req.execute } threads.join_nowait(t) end if @landing_page.browse_dimension_1 @browse_dim_thread_1 = Thread.new(@landing_page.browse_dimension_1, @nav_state) { |d,ns| load_browse_dimension_values(d, ns) } threads.join_nowait(@browse_dim_thread_1) end if @landing_page.browse_dimension_2 @browse_dim_thread_2 = Thread.new(@landing_page.browse_dimension_2, @nav_state) { |d,ns| load_browse_dimension_values(d, ns) } threads.join_nowait(@browse_dim_thread_2) end # wait at most 'secs' seconds for all modules to return secs = OperatingParamCache.instance.parallel_nav_module_timeout.to_i Timeout::timeout(secs) do |l| logger.debug "Wating for threads #{threads.inspect}" if logger.debug? ret = threads.all_waits logger.debug "Group #{threads.inspect} finished with ret #{ret.inspect}" if logger.debug? end rescue Timeout::Error logger.error "Navigation modules queries timed out in load_intermediate_modules" ensure # move valid results into @product_module_hash for display logger.debug "processing parallel query resutls" if logger.debug? res_hash.each do |lpr,p| if res_hash[lpr] && res_hash[lpr].status == false logger.debug "loading result for #{lpr}, thread #{res_hash[lpr]}" if logger.debug? endeca_response_to_module_hash lpr, res_hash[lpr].value else logger.debug "canceling thread for #{lpr} (#{res_hash[lpr]})" if logger.debug? res_hash[lpr][:request].cancel unless res_hash[lpr].blank? || res_hash[lpr][:request].blank? end end if @browse_dim_thread_1 && @browse_dim_thread_1.status == false logger.debug "loading result for browse_dim_thread_1, thread #{@browse_dim_thread_1}" if logger.debug? @browse_dimension_1_dim_values = @browse_dim_thread_1.value end if @browse_dim_thread_2 && @browse_dim_thread_2.status == false logger.debug "loading result for browse_dim_thread_2, thread #{@browse_dim_thread_2}" if logger.debug? @browse_dimension_2_dim_values = @browse_dim_thread_2.value end end end def load_modules_in_series @product_modules.each do |lpr| ns = create_nav_state_for_product_module_source lpr endeca_res = Endeca::execute ns.endeca_opts endeca_response_to_module_hash lpr, endeca_res end end def endeca_response_to_module_hash(lpr, endeca_res) if endeca_res.blank? # weird, no items found, but at least throw it at the end of the links @product_links << lpr else @product_modules_hash[lpr] = { :products => Product.from_endeca_response(endeca_res, :include => [:category, {:stat=>:representative_review}, {:partner_products =>:prices}, :primary_photo_association, :remote_photos]), :seo_snippet => lpr.seo_snippet } end end def create_nav_state_for_product_module_source(lpr, sort=nil) sort ||= 'product_score-1' logger.debug "Creating NavState for #{lpr.child.inspect}" if logger.debug? n = lpr.child.perma_n n += ' ' + @extra_n unless @extra_n.blank? ns = NavState.new :N => n, :sort => sort, :force_per_page => lpr.max_products ns[:l] = @nav_state[:l] if @nav_state.local? ns[:dist] = @nav_state[:dist] if @nav_state.local? ns end def load_landing_page_info if @landing_page info = @landing_page.info # always load this info @title = info.page_title unless info.page_title.blank? @page_headline = info.page_headline unless info.page_headline.blank? # only load this info when we want it shown and indexed logger.debug "XXX KML @meta_noindex '#{@meta_noindex.inspect}'" unless @meta_noindex == true @meta_keywords = info.meta_keywords unless info.meta_keywords.blank? @meta_description = info.meta_description unless info.meta_description.blank? @seo_text = info.seo_text unless info.seo_text.blank? @seo_links = [] 6.times { |i| url = info.send("seo_link_#{i}_url") text = info.send("seo_link_#{i}_text") @seo_links << Hash[:url => url, :text => text] unless url.blank? || text.blank? } end end end def configure_analytics(mode = nil) leaf = false if @landing_page cat_trail = Array.new cat_trail = @landing_page.category.primary_trail.collect { |c| c.name } if @landing_page.category cat_trail << "Landing Page #{@landing_page.permalink}" unless @landing_page.category_only? cat_trail = ['__root__', 'Site Wide Landing Page', @landing_page.permalink] unless @landing_page.category leaf = @landing_page.leaf? elsif @category cat_trail = @category.primary_trail.collect { |c| c.name } if @landing_page.category leaf = @category.leaf? end if params[:N] && @endeca_res && cat_trail cat_trail << "#{cat_trail[-1]} with facets" # trans_n = @web_analytics.breadcrumbs_to_text(@endeca_res.breadcrumbs) # @web_analytics.facet_nav(trans_n,session[:last_n_value],nil) # session[:last_n_value] = trans_n else # no N, clear the session session[:last_n_value] = nil end @web_analytics.category_trail(cat_trail, leaf, mode, params[:page]) end def cacheable? return false if session_user || session[:partner_style] || params[:partner_style] request.query_string.blank? && cookies['navsize'].blank? && cookies['navmode'].blank? end end
class Striuct; module InstanceMethods # @group Compare with other # @return [Boolean] def ==(other) other.instance_of?(self.class) && each_pair.all?{|autonym, val|other._get(autonym) == val} end alias_method :===, :== def eql?(other) other.instance_of?(self.class) && other._db.eql?(@db) end # @return [Integer] def hash @db.hash end protected def _db @db end # @endgroup end; end
class AddDetailsToWorks2 < ActiveRecord::Migration def change add_column :works, :year, :integer add_column :works, :kee, :string add_column :works, :opus, :string end end
class ArticlesController < ApplicationController before_action :find_article, only: [:show, :edit, :update, :destroy] #pass the method name :find_article, and it runs this before anything else #Give user ability to create new articles def new @article = Article.new #the whole form is like a blank article end #Create new article def create # render plain: params[:article].inspect @article = Article.new(article_params) #only allows certain parameters to be submitted. article_params (a private method) is required, which in turn only permits title and body. if @article.save # if article is sucessfully saved,... redirect_to @article # then redirect to that article... else render :new # otherwise, render the form again, so user can correct mistakes end end #Show specific article def show @article = Article.find(params[:id]) end #List all articles def index @articles = Article.all # .all class method on Article class end #Find specific article to edit def edit # @article = Article.find(params[:id]) #private method find_article applies to all routes, so load it as before_action (above) end #Update article def update # @article = Article.find(params[:id]) #see 'before_action' above if @article.update_attributes(article_params) redirect_to @article else render :edit end #Destroy article def destroy #no view needed for the delete method # @article = Article.find(params[:id]) @article.destroy redirect_to article_path end private #only allows these methods to be accessible to an instance of a class. can't be directly called by user. def article_params params.require(:article).permit(:title, :body) #only these parameters are allowed to be submitted by user. end def find_article @article = Article.find(params[:id]) #this allows you to delete it everywhere else end end
class Triangle define_method(:initialize) do |side1, side2, side3| @side1 = side1 @side2 = side2 @side3 = side3 end define_method(:triangle?) do @side1+@side2>@side3 || @side1+@side3>@side2 || @side2+@side3>@side1 end define_method(:equilateral?) do @side1 == @side2 && @side1 == @side3 end define_method(:isosceles?) do (@side1 == @side2 && @side1 != @side3) || (@side1 == @side3 && @side1 != @side2) || (@side2 == @side3 && @side2 != @side1) end define_method(:scalene?) do @side1 != @side2 && @side1 != @side3 && @side2 != @side3 end end
class CreateWorks < ActiveRecord::Migration def self.up create_table :works do |t| t.integer :composer_id t.string :work_name t.integer :work_order_id t.string :arr_orch t.boolean :showarrorch t.string :opus_no t.string :notes t.string :source t.timestamps end end def self.down drop_table :works end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html devise_for :users, controllers: { registrations: 'users/registrations' } resources :homeworks root to: 'homeworks#taks_list' resources :registries end
require 'spec_helper' require 'account' describe 'account feature' do context('transactions') do it('allows a user to deposit funds into their account') do account = Account.new expect { account.deposit(5) }.not_to raise_error end it('allows a user to withdraw funds into their account if they have enough funds') do account = Account.new account.deposit(10) expect { account.withdraw(5) }.not_to raise_error end it('does not allow a user to withdraw funds if they have insuficcient funds') do account = Account.new expect { account.withdraw(5) }.to raise_error end it('adds a deposit transaction to the transactions array') do account = Account.new expect { account.deposit(100) }.to change { account.transactions.length }.by(1) end it('adds a withdrawl transaction to the transactions array') do account = Account.new account.deposit(100) expect { account.withdraw(50) }.to change { account.transactions.length }.by(1) end it('prints out a statement') do statement = Statement.new account = Account.new(statement) account.deposit(100) account.withdraw(50) expect { account.print_statement }.not_to raise_error end end end
require 'spec_helper' describe CreateReputationEntry do let(:user) { FactoryGirl.create :user } let(:description) { "Foo" } let(:amount) { 10 } subject { CreateReputationEntry.new.(user, amount: amount, description: description) } it 'creates a ReputationEntry instance' do expect{ subject }.to change(ReputationEntry, :count).by 1 end it 'assigns the entry to the reputation' do expect(subject.reputation).to eq user.reputation end it 'adjusts the user\'s reputation balance' do expect{ subject }.to change(user.reputation, :balance).by amount end context 'if the amount is a decimal' do subject { CreateReputationEntry.new.(user, amount: @amount, description: description) } it 'rounds the amount up' do @amount = 10.1 expect(subject.amount).to eq 11 @amount = 10.5 expect(subject.amount).to eq 11 @amount = 10.75 expect(subject.amount).to eq 11 end end context 'when the entry amount would give the user a negative reputation' do let(:amount) { -10 } before do FactoryGirl.create :reputation_entry, reputation: user.reputation, amount: 5 expect(user.reputation.balance).to eq 5 end it 'limits the amount to the amount that won\'t drop the reputation below 0' do expect{ subject }.to change(user.reputation, :balance).to 0 expect(subject.amount).to eq -5 end end context 'when an entry_name is provided' do subject { CreateReputationEntry.new.(user, entry_name: :initial_value, amount: 10)} it 'retrieves the description based on the entry_name' do expect(subject.description).to eq I18n.t('reputation_entry.initial_value') end end describe '.tip_marked_helpful' do let(:tipper) { instance_double "User" } let(:tip) { instance_double "Tip", user: tipper, id: 1 } let(:purchaser) { instance_double "User", reputation: reputation } let(:purchase) { instance_double "Purchase", user: purchaser, tip: tip } let(:reputation) { instance_double "Reputation", balance: 100 } let(:impact) { instance_double "Impact", purchase: purchase } subject { described_class.tip_marked_helpful(impact) } it 'sets the amount to 1' do expect_any_instance_of(described_class).to receive(:call). with tipper, hash_including(amount: 1) subject end it 'calculates the amount as 1/100 (ceiling rounded) of the purchaser reputation' do allow(reputation).to receive(:balance).and_return 501 expect_any_instance_of(described_class).to receive(:call). with tipper, hash_including(amount: 6) subject end end describe '.tip_marked_not_helpful' do let(:tipper) { instance_double "User" } let(:tip) { instance_double "Tip", user: tipper, id: 1 } let(:purchaser) { instance_double "User", reputation: reputation } let(:purchase) { instance_double "Purchase", user: purchaser, tip: tip } let(:reputation) { instance_double "Reputation", balance: 100 } let(:impact) { instance_double "Impact", purchase: purchase } subject { described_class.tip_marked_not_helpful(impact) } it 'sets the amount to 1' do expect_any_instance_of(described_class).to receive(:call). with tipper, hash_including(amount: -1) subject end it 'calculates the amount as 1/100 (ceiling rounded) of the purchaser reputation' do allow(reputation).to receive(:balance).and_return 501 expect_any_instance_of(described_class).to receive(:call). with tipper, hash_including(amount: -6) subject end end end
describe "Company" do before :all do @test_company = Company.new "Test Company" @manager = Manager.new "ClayManager" @h_employee = HourlyEmployee.new "ClayHourly" end describe "#initialize" do it "should instantiate without problems" do test = Company.new "Test Corp" expect(test).not_to be_nil expect(test.name).to eq("Test Corp") end end describe "#hire" do it "should be able to hire an employee" do employee = Employee.new "ClayEmployee" num_employees = @test_company.hire(employee) expect(num_employees).to eq(1) end it "should be able to hire an hourly employee" do num_employees = @test_company.hire(@h_employee) expect(num_employees).to eq(2) end it "should be able to hire a salaried employee" do s_employee = SalariedEmployee.new "ClaySalaried" num_employees = @test_company.hire(s_employee) expect(num_employees).to eq(3) end it "should be able to hire an executive" do executive = Executive.new "ClayExecutive" num_employees = @test_company.hire(executive) expect(num_employees).to eq(4) end it "should be able to hire a manager" do num_employees = @test_company.hire(@manager) expect(num_employees).to eq(5) end end describe "#fire" do it "should be able to fire an employee by name" do removed = @test_company.fire("ClayHourly") expect(removed.name).to eq("ClayHourly") expect(@test_company.employees.count).to eq(4) end it "should be able to fire an employee by id" do removed = @test_company.fire(3) expect(removed.name).to eq("ClaySalaried") expect(@test_company.employees.count).to eq(3) end it "should be able to fire an employee given an employee" do removed = @test_company.fire(@manager) expect(removed).to eq(@manager) expect(@test_company.employees.count).to eq(2) end end describe "#raise" do it "should be able to increase the pay of a named employee by a given percentage" do @test_company.hire(@h_employee) emp = @test_company.employees.find { |e| e.name == "ClayHourly" } @test_company.give_raise("ClayHourly", 0.10) expect(emp.payrate).to eq(7.98) end end end
class RealEstatesController < ApplicationController before_action :set_real_estate, only: [:show, :edit, :update, :destroy] before_action :confirm_realestate_ready, only: [:show] before_action :autherize_user, only: [:new, :create, :edit, :destroy] before_action :authenticate_user!, only: [:current_user_offers, :current_user_favorites] before_action :confirm_ownership, only: [:edit] # GET /real_estates # GET /real_estates.json def index @real_estates = real_estate_class.ready.ordered.page params[:page] end # GET /real_estates/1 # GET /real_estates/1.json def show; end # GET /real_estates/new def new @real_estate = real_estate_class.new end # GET /real_estates/1/edit def edit; end # POST /real_estates # POST /real_estates.json def create @real_estate = RealEstate.new(real_estate_params) respond_to do |format| if params[:pictures] params[:pictures].each do |pic| @real_estate.pictures.build avatar: pic end end if @real_estate.save format.html { redirect_to @real_estate, notice: 'Real estate was successfully created.' } format.json { render :show, status: :created, location: @real_estate } else format.html { render :new } format.json { render json: @real_estate.errors, status: :unprocessable_entity } end end end # PATCH/PUT /real_estates/1 # PATCH/PUT /real_estates/1.json def update respond_to do |format| if @real_estate.update(real_estate_params) if params[:pictures] params[:pictures].each do |pic| @real_estate.pictures.create! avatar: pic end end format.html { redirect_to @real_estate, notice: 'Real estate was successfully updated.' } format.json { render :show, status: :ok, location: @real_estate } else format.html { render :edit } format.json { render json: @real_estate.errors, status: :unprocessable_entity } end end end # DELETE /real_estates/1 # DELETE /real_estates/1.json def destroy @real_estate.destroy respond_to do |format| format.html { redirect_to real_estates_url, notice: 'Real estate was successfully destroyed.' } format.json { head :no_content } end end def current_user_offers @real_estates = real_estate_class.where(user: current_user).ordered.page params[:page] render 'index' end def current_user_favorites @real_estates = current_user.get_voted(real_estate_class).ordered.page params[:page] render 'index' end private def set_real_estate @real_estate = real_estate_class.find(params[:id]) end def confirm_realestate_ready redirect_to root_url unless @real_estate.status.ready? end def real_estate_params params.require(real_estate_type.underscore.to_sym) .permit(:title, :type, :address_id, :area, :price, :storey, :description, :has_balcony, :furnished, :has_roof, :has_garden, :has_elevator, :created_at, :rooms, :baths, :offer_type, :rent_type, :featured, :pictures, :number_of_storeies, :number_of_flats) end def real_estate_type RealEstate.type.values.include?(params[:type]) ? params[:type] : 'RealEstate' end def real_estate_class @real_estate_class = real_estate_type.constantize end def autherize_user authenticate_user! redirect_to new_user_profile_path(current_user) unless current_user.profile_ready? end def confirm_ownership return if user_signed_in? && current_user == @real_estate.user flash[:warning] = 'لا تمتلك الصلاحيات اللازمة' redirect_to root_url end end
class ApplicationController < ActionController::Base include ApplicationHelper # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception #render 404 error def not_found raise ActionController::RoutingError.new('Not Found') end rescue_from CanCan::AccessDenied do |exception| redirect_to page_path('blank'), :alert => exception.message end ##Override the devise default redirect path def after_sign_in_path_for(resource) if resource.sites.any? sites_path else page_path('dashboard') end end #obj = site/site_page #call on controller: before_filter -> { authorize! @site }, only: [:edit, :update, :destroy] #call on action: authorize!(@site) def authorize!(obj) ids = [obj.try(:user_id), obj.try(:site).try(:user_id)] return if ids.compact.empty? if !ids.include?(current_user.id) raise CanCan::AccessDenied.new('没有权限!' ) end end private def mobile_device? request.user_agent =~ /Mobile|webOS/ end helper_method :mobile_device? def prepare_for_mobile session[:mobile_param] = params[:mobile] if params[:mobile] end end
#!/usr/bin/env ruby # frozen_string_literal: true def fibs(number) fibonacci_values = [] 0.upto(number - 1) do |value| next fibonacci_values << value if value < 2 fibonacci_values << fibonacci_values[-1] + fibonacci_values[-2] end fibonacci_values end puts 'Fibonacci Iteration: ' p fibs(5) p fibs(4) p fibs(14) p fibs(1) p fibs(0) puts # def fibs_rec(number, fib = [0, 1]) # number < 3 ? fib : fibs_rec(number - 1, fib << fib[-1] + fib[-2]) # end def fibs_rec(number, fib = [0, 1]) return [] if number <= 0 return [0] if number == 1 return fib if number == 2 fibs_rec(number - 1, fib << fib[-1] + fib[-2]) end puts 'Fibonacci Recursion: ' p fibs_rec(5) p fibs_rec(4) p fibs_rec(14) p fibs_rec(1) p fibs_rec(0)
# == Schema Information # # Table name: users # # id :uuid not null, primary key # name :string # created_at :datetime not null # updated_at :datetime not null # class User < ApplicationRecord has_one :join has_one :hand, class_name: 'Field::Hand', through: :seat has_one :river, class_name: 'Field::River', through: :seat has_one :room, through: :join has_one :game, through: :room has_one :seat end
require 'rails_helper' RSpec.describe Api::V1::PlanetarySystemsController, type: :controller do describe 'GET #index' do before do PlanetarySystem.create!(name: 'Solar System') get :index, format: :json end it 'returns a successful response' do expect(response).to be_successful expect(response).to have_http_status(200) end it 'contains planetary systems records' do json = response.body ps = parse_json(json).first expect(json).to have_json_size(1) expect(ps['name']).to eq('Solar System') end end end
require 'test_helper' module Sources class DeviantArtTest < ActiveSupport::TestCase context "The source for a private DeviantArt image URL" do setup do @site = Sources::Site.new("https://pre00.deviantart.net/423b/th/pre/i/2017/281/e/0/mindflayer_girl01_by_nickbeja-dbpxdt8.png") @site.get end should "work" do assert_equal(["https://pre00.deviantart.net/423b/th/pre/i/2017/281/e/0/mindflayer_girl01_by_nickbeja-dbpxdt8.png"], @site.image_urls) end end context "The source for a download-disabled DeviantArt artwork page" do should "get the image url" do @site = Sources::Site.new("https://noizave.deviantart.com/art/test-no-download-697415967") assert_equal(["https://img00.deviantart.net/56ee/i/2017/219/2/3/test__no_download_by_noizave-dbj81lr.jpg"], @site.image_urls) end end context "The source for a DeviantArt image url" do should "fetch the source data" do @site = Sources::Site.new("https://pre00.deviantart.net/b5e6/th/pre/f/2016/265/3/5/legend_of_galactic_heroes_by_hideyoshi-daihpha.jpg") assert_equal("hideyoshi", @site.artist_name) assert_equal("https://hideyoshi.deviantart.com", @site.profile_url) assert_equal("https://orig00.deviantart.net/9e1f/f/2016/265/3/5/legend_of_galactic_heroes_by_hideyoshi-daihpha.jpg", @site.image_url) end end context "The source for an DeviantArt artwork page" do setup do @site = Sources::Site.new("http://noizave.deviantart.com/art/test-post-please-ignore-685436408") @site.get end should "get the image url" do assert_match(%r!https?://origin-orig.deviantart.net/7b5b/f/2017/160/c/5/test_post_please_ignore_by_noizave-dbc3a48.png!, @site.image_url) end should "get the profile" do assert_equal("https://noizave.deviantart.com", @site.profile_url) end should "get the artist name" do assert_equal("noizave", @site.artist_name) end should "get the tags" do assert_equal(%w[bar baz foo], @site.tags.map(&:first)) end should "get the artist commentary" do title = "test post please ignore" desc = "<div align=\"center\"><span>blah blah<br /><div align=\"left\"><a class=\"external\" href=\"https://www.deviantart.com/users/outgoing?http://www.google.com\">test link</a><br /></div></span></div><br /><h1>lol</h1><br /><br /><b>blah</b>&nbsp;<i>blah</i>&nbsp;<u>blah</u>&nbsp;<strike>blah</strike><br />herp derp<br /><br /><blockquote>this is a quote</blockquote><ol><li>one</li><li>two</li><li>three</li></ol><ul><li>one</li><li>two</li><li>three</li></ul><img src=\"https://e.deviantart.net/emoticons/h/heart.gif\" alt=\"Heart\" style=\"width: 15px; height: 13px;\" data-embed-type=\"emoticon\" data-embed-id=\"357\">&nbsp;&nbsp;" assert_equal(title, @site.artist_commentary_title) assert_equal(desc, @site.artist_commentary_desc) end should "get the dtext-ified commentary" do desc = <<-EOS.strip_heredoc.chomp blah blah "test link":[http://www.google.com] h1. lol [b]blah[/b] [i]blah[/i] [u]blah[/u] [s]blah[/s] herp derp [quote]this is a quote[/quote] * one * two * three * one * two * three "Heart":[https://e.deviantart.net/emoticons/h/heart.gif] EOS assert_equal(desc, @site.dtext_artist_commentary_desc) end end context "The source for a login-only DeviantArt artwork page" do setup do @site = Sources::Site.new("http://noizave.deviantart.com/art/hidden-work-685458369") @site.get end should "get the image url" do assert_match(%r!https?://origin-orig\.deviantart\.net/cb25/f/2017/160/1/9/hidden_work_by_noizave-dbc3r29\.png!, @site.image_url) end end context "A source with malformed links in the artist commentary" do should "fix the links" do @site = Sources::Site.new("https://teemutaiga.deviantart.com/art/Kisu-620666655") @site.get assert_match(%r!"Print available at Inprnt":\[http://www.inprnt.com/gallery/teemutaiga/kisu\]!, @site.dtext_artist_commentary_desc) end end end end
class AddPaymentstatusToReservations < ActiveRecord::Migration def change add_column :reservations, :paymentstatus, :integer end end
require 'spec_helper' require 'natives/host_detection/package_provider' describe Natives::HostDetection::PackageProvider do it "detects host's package provider name" do platform = double() platform.should_receive(:name).and_return('ubuntu') package_provider = Natives::HostDetection::PackageProvider.new(platform) expect(package_provider.name).to eq('apt') end it "returns first package provider that exists in host" do platform = double() package_provider = Natives::HostDetection::PackageProvider.new(platform) platform.should_receive(:name).and_return('mac_os_x') package_provider.should_receive(:which).with('brew').and_return(nil) package_provider.should_receive(:which). with('port').and_return('/path/to/port') expect(package_provider.name).to eq('macports') end it "returns nil when detection fails" do platform = double() platform.should_receive(:name).and_return('unknown') package_provider = Natives::HostDetection::PackageProvider.new(platform) expect(package_provider.name).to be_nil end end
class MeetingRoomsController < ApplicationController before_action :authenticate_user! load_and_authorize_resource before_action :set_meeting_room, only: [:show, :edit, :update, :destroy] # GET /meeting_rooms # GET /meeting_rooms.json def index @meeting_rooms = MeetingRoom.where("true").order(:name).page params[:page] end # GET /meeting_rooms/1 # GET /meeting_rooms/1.json def show end # GET /meeting_rooms/new def new @meeting_room = MeetingRoom.new end # GET /meeting_rooms/1/edit def edit end # POST /meeting_rooms # POST /meeting_rooms.json def create @meeting_room = MeetingRoom.new(meeting_room_params) respond_to do |format| if @meeting_room.save format.html { redirect_to @meeting_room, notice: 'Meeting room was successfully created.' } format.json { render :show, status: :created, location: @meeting_room } else format.html { render :new } format.json { render json: @meeting_room.errors, status: :unprocessable_entity } end end end # PATCH/PUT /meeting_rooms/1 # PATCH/PUT /meeting_rooms/1.json def update respond_to do |format| if @meeting_room.update(meeting_room_params) format.html { redirect_to @meeting_room, notice: 'Meeting room was successfully updated.' } format.json { render :show, status: :ok, location: @meeting_room } else format.html { render :edit } format.json { render json: @meeting_room.errors, status: :unprocessable_entity } end end end # DELETE /meeting_rooms/1 # DELETE /meeting_rooms/1.json def destroy @meeting_room.destroy respond_to do |format| format.html { redirect_to meeting_rooms_url, notice: 'Meeting room was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_meeting_room @meeting_room = MeetingRoom.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def meeting_room_params params.require(:meeting_room).permit(:name, :floor_no) end end
class SuppliersController < ApplicationController #helper_method :sort_column, :sort_direction set_tab :suppliers def index @suppliers = current_company.suppliers respond_to do |format| format.html # index.html.erb format.json { render json: @suppliers } end end def show @supplier = Supplier.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @supplier } end end def new @supplier = current_company.suppliers.build respond_to do |format| format.html # new.html.erb format.modal { render action: :new, formats: [:html], layout: false } end end def edit @supplier = Supplier.find(params[:id]) end def create @supplier = current_company.suppliers.build(params[:supplier]) respond_to do |format| if @supplier.save format.html { redirect_to @supplier, notice: 'Supplier was successfully created.' } format.json { render json: @supplier, status: :created, location: @supplier } else format.html { render action: "new" } format.json { render json: @supplier.errors, status: :unprocessable_entity } end end end def update @supplier = Supplier.find(params[:id]) respond_to do |format| if @supplier.update_attributes(params[:supplier]) format.html { redirect_to @supplier, notice: 'Supplier was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @supplier.errors, status: :unprocessable_entity } end end end def destroy @supplier = Supplier.find(params[:id]) @supplier.destroy respond_to do |format| format.html { redirect_to suppliers_url } format.json { head :no_content } end end end
# encoding: UTF-8 class Mental < ActiveRecord::Base attr_accessible :description, :title, :kid_id validates :title, :uniqueness => {:message => 'عنوان تکراری است'} validates :title, :presence => {:message => 'عنوان را بنویسید'} has_and_belongs_to_many :kids end
require 'kuhsaft/page_tree' module Kuhsaft module Cms class PagesController < AdminController def index @pages = Kuhsaft::Page.roots respond_with @pages end def show @page = Kuhsaft::Page.find(params[:id]) respond_with @page end def new @page = Kuhsaft::Page.new @page.published ||= Kuhsaft::PublishState::UNPUBLISHED respond_with @page end def create @page = Kuhsaft::Page.create(page_params) if @page.valid? flash[:success] = t('layouts.kuhsaft.cms.flash.success', subject: Kuhsaft::Page.model_name.human) respond_with @page, location: kuhsaft.edit_cms_page_path(@page) else render 'new' end end def edit @page = Kuhsaft::Page.find(params[:id]) @page.published ||= Kuhsaft::PublishState::UNPUBLISHED @page.bricks.each { |brick| brick.valid? } respond_with @page end def update @page = Kuhsaft::Page.find(params[:id]) if @page.update_attributes(page_params) flash[:success] = t('layouts.kuhsaft.cms.flash.success', subject: Kuhsaft::Page.model_name.human) respond_with @page, location: kuhsaft.edit_cms_page_path(@page) else render 'edit' end end def destroy @page = Kuhsaft::Page.find(params[:id]) @page.destroy redirect_to kuhsaft.cms_pages_path end def sort Kuhsaft::PageTree.update(params[:page_tree]) end def mirror @page = Kuhsaft::Page.find(params[:page_id]) unless @page.bricks.empty? if params[:rutheless] == 'true' || @page.bricks.unscoped.where(locale: params[:target_locale]).empty? @page.clear_bricks_for_locale(params[:target_locale]) params[:failed_bricks] = @page.clone_bricks_to(params[:target_locale]) params[:rutheless] = 'true' end end respond_to :js, :html end private def page_params safe_params = [ :title, :page_title, :slug, :redirect_url, :url, :page_type, :parent_id, :keywords, :description, :published, :position, :google_verification_key ] params.require(:page).permit(*safe_params) end end end end
class ForumSerializer < ActiveModel::Serializer attributes :id, :name, :slug has_many :posts has_many :users, through: :posts end
require 'spec_helper' describe 'sabnzbd', :type => 'class' do context "On Debian OS" do let :facts do { :operatingsystem => 'Debian' } end it { should contain_package('unrar-free') } end context "On Ubuntu OS" do let :facts do { :operatingsystem => 'Ubuntu' } end it { should contain_package('unrar') } end context "On any system with a different user specified" do let :params do { :user => 'mediauser' } end it { should contain_user('mediauser') } end end
require 'test_helper' class UserTest < ActiveSupport::TestCase # Test Validations should have_secure_password should validate_presence_of(:username) should validate_uniqueness_of(:username) # Scope and method tests context "With a proper context, " do setup do create_users end teardown do remove_users end should "Show users in alphabetical order" do assert_equal [@userAdmin, @user2, @user3], User.alphabetical.map { |e| e } end should "Show active users" do assert_equal [@userAdmin, @user2], User.active.alphabetical.map { |e| e } end should "Show inactive users" do assert_equal [@user3], User.inactive.alphabetical.map { |e| e } end should "Find by username" do assert_equal [@userAdmin], User.find_by_username("admin") end end end
require 'test_helper' class CompanyFieldsControllerTest < ActionController::TestCase setup do @company_field = company_fields(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:company_fields) end test "should get new" do get :new assert_response :success end test "should create company_field" do assert_difference('CompanyField.count') do post :create, company_field: { name: @company_field.name } end assert_redirected_to company_field_path(assigns(:company_field)) end test "should show company_field" do get :show, id: @company_field assert_response :success end test "should get edit" do get :edit, id: @company_field assert_response :success end test "should update company_field" do patch :update, id: @company_field, company_field: { name: @company_field.name } assert_redirected_to company_field_path(assigns(:company_field)) end test "should destroy company_field" do assert_difference('CompanyField.count', -1) do delete :destroy, id: @company_field end assert_redirected_to company_fields_path end end
class UserExerciseSerializer < ActiveModel::Serializer attributes :id, :user_id, :exercise_id, :reps, :weight, :created_at end
class ChangeShopTierTypeInUsers < ActiveRecord::Migration def change change_column :users, :shopTier, :text, default: 1 change_column :users, :email, :string, :null => false change_column :users, :crypted_password, :string, :null => false change_column :users, :salt, :string, :null => false end end
class AddFieldsToFeed < ActiveRecord::Migration[6.1] def change add_reference :feeds, :saved_search, index: true add_reference :feeds, :user, index: true add_reference :feeds, :team, index: true add_column :feeds, :description, :text add_column :feeds, :tags, :string, array: true, default: [] add_column :feeds, :licenses, :integer, array: true, default: [] # Remove filters column remove_column :feeds, :filters end end
require 'faker' require 'time' require 'csv' =begin * Crear la clase Person con los siguientes atributos: first_name, last_name, email, phone, created_at * Crear un método que reciba como argumento el número de personas que quieres crear. Y regrese las personas en un arreglo. * Faker es una librería de Ruby que nos permite generar información falsa para poder simular el comportamiento del programa con datos. =end class Person attr_accessor :first_name, :last_name, :email, :phone, :created_at def initialize(first_name, last_name, email, phone, created_at) @first_name = first_name @last_name = last_name @email = email @phone = phone @created_at = created_at end def self.create_people(num_people) @array_people = [] @num_people = num_people @num_people.times do @array_people << Person.new(Faker::Name.first_name, Faker::Name.last_name, Faker::Internet.email, Faker::PhoneNumber.phone_number, created_at = Time.now) end @array_people end end class PersonWriter attr_accessor :file def initialize(file, array) @file = file @people = array end def create_csv CSV.open(@file, "wb") do |csv| @people.each do |person| csv << [person.first_name , person.last_name, person.email, person.phone, person.created_at] end end end end class PersonParser attr_accessor :array_persons def initialize(file) @file = file end def people @array_persons = [] csv_array_persons = CSV.read(@file) csv_array_persons.each do |row| @array_persons << Person.new(row[0], row[1], row[2], row[3], row[4]) end p @array_persons[0..9] end end class Modified def initialize(file) @file = file end def people @array_persons = [] csv_array_persons = CSV.read(@file) csv_array_persons.each do |row| @array_persons << Person.new(row[0], row[1], row[2], row[3], row[4]) end @array_persons end def insert_name puts "insert name for search in database" @name_for_search = gets.chomp search_name end def search_name people @array_persons.each do |person| if @name_for_search == person.first_name person.email = Faker::Internet.email end end @array_persons create_csv end def create_csv CSV.open(@file, "wb") do |csv| @array_persons.each do |person| csv << [person.first_name, person.last_name, person.email, person.phone, person.created_at] end end end end people = Modified.new('people.csv') people.insert_name
require_relative 'piece.rb' require 'colorize' class Board attr_accessor :cursor, :selector attr_reader :grid def initialize @grid = Array.new(10) { Array.new(10) { EmptySquare.new } } populate @cursor = [5,5] @selector = [] end def move_cursor(change) new_cursor = [@cursor[0] + change[0], @cursor[1] + change[1]] row, col = new_cursor @cursor = new_cursor if row.between?(0, 9) && col.between?(0, 9) end def [](position) row, col = position @grid[row][col] end def []=(position, piece) row, col = position @grid[row][col] = piece end def populate (0..9).each_with_index do |row| (0..9).each_with_index do |col| if row < 3 && (row - col).odd? self[[row, col]] = Piece.new(:black, [row, col], self) elsif row > 6 && (row - col).odd? self[[row, col]] = Piece.new(:white, [row, col], self) end end end end def display system('clear') grid.each_with_index do |row, row_idx| row.each_with_index do |piece, col_idx| if cursor == [row_idx, col_idx] print " #{piece} ".colorize(:background => :yellow) elsif selector == [row_idx, col_idx] print " #{piece} ".colorize(:background => :light_red) elsif (row_idx - col_idx) % 2 > 0 print " #{piece} ".colorize(:background => :cyan) else print " #{piece} ".colorize(:background => :white) end end puts end end def is_enemy?(position, color) self[position].color != :empty && self[position].color != color end def no_object?(position) row, col = position row.between?(0, 9) && col.between?(0, 9) && self[position].empty? end def must_jump?(color) get_color_pieces(color).any? { |piece| piece.can_jump? } end def get_color_pieces(color) @grid.flatten.select { |piece| piece.color == color } end end
Rails.application.routes.draw do devise_for :users root 'posts#index' # delete 'posts/:id' => 'posts#destroy' resources :users, only: [:show, :edit, :update] resources :posts, only: [:new, :create, :show] end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] # GET /users # GET /users.json def index @users = User.all end # GET /users/1 # GET /users/1.json def user_my_page @user = User.find_by(uid: session[:user_id]) render :show end # GET /users/1/edit def edit end def sign_in render 'users/sign_in' end def sign_in_authentication if (user = User.find_by(mail: params[:mail])) && user.authenticate(params[:password]) session[:user_id] = user.uid redirect_to :root else render :text => 'パスワードまたはメールアドレスが異なります' end end def sign_out session.clear redirect_to :root end def sign_up #new @user = User.new render 'users/new' end # POST /users # POST /users.json def create @user = User.new(user_params) @user.uid = SecureRandom.uuid @user.sex = "0" respond_to do |format| if @user.save session[:user_id] = @user.uid redirect_to :root else format.html { render :new } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update respond_to do |format| if @user.update(user_params) format.html { redirect_to @user, notice: 'User was successfully updated.' } format.json { render :show, status: :ok, location: @user } else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json def destroy @user.destroy respond_to do |format| format.html { redirect_to users_url, notice: 'User was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find_by(uid: params[:uid]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params return params.require(:user).permit(:uid, :mail, :password, :password_confirmation, :address, :birthday, :sex) end end
require 'fog' class Ec2Driver < Provider PROVIDER='Amazon/AWS' LOG_PROVIDER='ec2' MAXJOBS = 2 PROVIDER_ID = 67 LOGIN_AS = 'ubuntu' DEFIMAGES = {'us-east-1' => 'ami-9a562df2', 'us-west-1' => 'ami-057f9d41', 'us-west-2' => 'ami-51526761', 'eu-west-1' => 'ami-2396f654', 'eu-central-1' => 'ami-00dae61d', 'ap-southeast-1' => 'ami-76546924', 'ap-southeast-2' => 'ami-cd611cf7', 'ap-northeast-1' => 'ami-c011d4c0', 'sa-east-1' => 'ami-75b23768' } @authlocs = {} def self.get_active location, all, &block s = get_auth location servers = s.servers.each do |server| if server.state == 'running' or all yield server.id, server.tags['Name'], server.public_ip_address, server.state end end end def self.create_server name, scope, flavor, loc if flavor['keyname'].blank? puts "must specify keyname" return nil end image = flavor['imageid'] image= DEFIMAGES[loc] if image.blank? server = self._create_server name, flavor['flavor'], loc, flavor['keyname'], image, false if server.nil? puts "can't create #{name}: #{server}" return nil end server.wait_for { server.ready? } rv = {} rv[:id] = server.id rv[:ip] = server.public_ip_address sleep 10 rv end def self.get_auth loc return @authlocs[loc] if @authlocs[loc] keys = get_keys loc @authlocs[loc] = Fog::Compute.new({:provider => 'AWS', :region => loc}.merge keys) end def self.get_keys loc super({:aws_access_key_id => nil, :aws_secret_access_key =>nil}, loc) end def self._create_server name, instance, loc, keyname, image, createvol=false s = get_auth loc server = s.servers.create(:image_id => image, :flavor_id => instance, :key_name => keyname, :tags => {Name: name}) server end end
module Communication def main_menu_prompt puts "Welcome to BATTLESHIP\n\n" puts "Would you like to (p)lay, read the (i)nstructions, " + "or (q)uit?\n" end def incorrect_input puts "Please re-enter your choice." end def show_game_instructions double_space puts "The game of BattleShip is played by you and the computer.\n" + "The gameboard is sized according to the difficulty selected.\n" + "First you and the computer will place ships on the board.\n" + "After placement, you will alternate firing at the enemy. The first\n" + "to hit and sink the opponent's ships, wins. Firing coordinates are\n" + "labeled by their columns, from 1 to n. Rows are labeled by letter from\n" + "the letter 'A'. Good luck, and may the best navy win!" double_space puts "Go (b)ack" end def select_difficulty double_space puts "Please select difficulty setting." puts "(b)eginner, (i)ntermediate, (a)dvanced" end def computer_placed_ships double_space puts "The computer has placed the ships on the board." end def player_place_ships_message(difficulty) start_grid = "A1" additional_units = "" case difficulty when "b" num_ships = 2 end_grid = "D4" when "i" num_ships = 3 end_grid = "H8" additional_units = "The third is four units long.\n" when "a" num_ships = 4 end_grid = "L12" additional_units = "The third is four units long.\n" + "The fourth is five units long.\n" end double_space puts "You now need to layout your #{num_ships} ships.\n" + "The first is two units long and the\n" + "second is three units long.\n" + additional_units + "The grid has #{start_grid} at the top left and #{end_grid} at the bottom right." end def enter_coordinates_message(ship_size) double_space puts "You are placing a ship of #{ship_size} units in length.\n" + "Please enter the beginning and end coordinates like so:\n" + "A1 D1" end def initiate_war_message double_space puts "You have set up your fleet just in time!\n" + "The enemy is now in range. For the MOTHERLAND!!!" end def player_shot_message double_space puts "Please enter a coordinate to target." end def already_fired_upon_message double_space puts "You have already fired on this target." end def computer_shot_message double_space puts "Computer is shooting" end def target_is_hit double_space puts "Target is hit." end def target_is_miss double_space puts "Target is missed." end def ship_hit_message(ship_type) double_space puts "The #{ship_type} unit ship has been hit." end def end_turn_message double_space puts "Press enter to end turn." end def shots_fired_message(grids_targeted) double_space puts "Number of shots fired by both sides is #{grids_targeted.size}." end def press_enter_message puts "Hit enter to end turn." end def ship_destroyed_message(ship_length) puts "The #{ship_length} unit ship has been destroyed." end def print_border(size) size.times do print "=====" end puts "\n" end def print_row_label(size) (size + 1).times do |num| if num == 0 print ". " elsif num > 9 print "#{num} " else print "#{num} " end end puts "\n" end def print_whole_board(board, letters) board.board.each_with_index do |row, index| letter = letters.key(index) print "#{letter} " row.each do |element| print "#{element} " end puts "\n" end end def player_loses_message double_space puts "Sorry but you lost, you loser. You lost to a program. SAD!" end def player_wins_message double_space puts "Congrats! You win. Now have a sucker." end def time_elapsed(start, finish) puts "Time elapsed: #{finish - start} seconds." end def player_board_title puts "Player Board\n" end def targeting_board_title puts "Target Board\n" end def double_space puts "\n\n" end end
class RostersController < ApplicationController before_action :set_roster, only: [:show, :edit, :update, :destroy] # GET /rosters # GET /rosters.json def index @rosters = Roster.all end # GET /rosters/1 # GET /rosters/1.json def show end # GET /rosters/new def new @roster = Roster.new end # GET /rosters/1/edit def edit end # POST /rosters # POST /rosters.json def create @roster = Roster.new(roster_params) respond_to do |format| if @roster.save format.html { redirect_to @roster, notice: 'Roster was successfully created.' } format.json { render :show, status: :created, location: @roster } else format.html { render :new } format.json { render json: @roster.errors, status: :unprocessable_entity } end end end # PATCH/PUT /rosters/1 # PATCH/PUT /rosters/1.json def update respond_to do |format| if @roster.update(roster_params) format.html { redirect_to @roster, notice: 'Roster was successfully updated.' } format.json { render :show, status: :ok, location: @roster } else format.html { render :edit } format.json { render json: @roster.errors, status: :unprocessable_entity } end end end # DELETE /rosters/1 # DELETE /rosters/1.json def destroy @roster.destroy respond_to do |format| format.html { redirect_to rosters_url, notice: 'Roster was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_roster @roster = Roster.find(params[:id]) end # Only allow a list of trusted parameters through. def roster_params params.require(:roster).permit(:title, :start_date, :finish_date, :volunteer_id, :organisation_id) end end
class CreateCustomers < ActiveRecord::Migration def change create_table :customers do |t| t.string :name t.string :category t.string :address t.string :city t.string :uf t.integer :km t.integer :zipcode t.string :phones t.string :email t.string :fb t.string :twitter t.string :instagram t.string :gplus t.text :menu t.text :about t.string :bussinesshours t.string :paymentmethods t.string :wifi t.float :latitude t.float :longitude t.string :logoimg t.timestamps null: false end end end
class AddBuySellToIndicators < ActiveRecord::Migration def change add_column :indicators, :action, :boolean end end
# frozen_string_literal: true class AreaCodeToState class << self def area_code_to_region(area_code) state = two_char_states.slice((area_code - 200) << 1, 2) return state unless state[0] == '.' case state[1] when ',' then nil when '>' then other_regions[area_code] else; state end end def valid_area_code?(val) int = Integer val rescue nil int&.between?(200, 999) && int end def two_char_states @two_char_states ||= File.read(path('area_code_regions_blob.txt')).chomp end def other_regions @other_regions ||= begin p = path 'area_codes_with_region_names_over_2_chars_long.txt' hash = {} File.foreach(p) do |line| hash[Integer line[0..2]] = line[3..-1].chomp end hash end end def path(file_name) File.join File.dirname(__FILE__), file_name end end attr_reader :area_code def initialize(area_code) @area_code = area_code end def call valid_area_code = self.class.valid_area_code? area_code raise ArgumentError, "Invalid area code: #{area_code.inspect}" unless valid_area_code self.class.area_code_to_region valid_area_code end end
FactoryBot.define do factory :drift do title "TestTitle" body "TestBodyTEEEEXT" end end
class Equipment < ActiveRecord::Base validates :sn, presence: true, uniqueness: true validates :user, presence: true validates :user_id, presence: true validates :category, presence: true belongs_to :user belongs_to :creator, class_name: 'User' has_many :transfers mount_uploader :image, ImageUploader def request_users User.where(id: transfers.where(state: "pending").pluck(:user_id)).pluck(:english_name).join(',') end def name return sn end state_machine :state, :initial => :normal do event :broke do transition :normal => :broken end end end
class EasyUserAllocationByProjectQuery < EasyUserAllocationQuery def query_after_initialize super self.easy_query_entity_action = 'by_project' end def available_filters return @available_filters unless @available_filters.blank? @available_filters = basic_filters.dup @available_filters.merge!(project_filters) @available_filters.merge!(user_filters) return @available_filters end def project_filters return @project_filters unless @project_filters.blank? @project_filters = {} EasyProjectQuery.new.available_filters.each do |name, f| @project_filters["project_#{name}"] = f @project_filters["project_#{name}"][:name] ||= I18n.translate("field_#{name.gsub(/_id$/, '')}") end @project_filters end def project_query query = EasyProjectQuery.new filters.each do |name, f| if name =~ /^project_/ query.add_filter name.gsub(/^project_/, ''), f[:operator], f[:values] end end query end def data_by_project(from, to) users = user_query.entities allocations = {} project_query.entities(:limit => 70).each do |project| users_allocations = project.easy_user_allocations. select('*, SUM(hours) as hours'). group(:user_id, :date). where(:date => from..to, :user_id => users). all.group_by(&:user_id) user_data = {} users.each do |user| if users_allocations.has_key?(user.id) user_data[user] = users_allocations[user.id] end end allocations[project] = user_data end allocations end def default_filter { 'range'=>{:operator=>'date_period_1', :values => HashWithIndifferentAccess.new({:period => 'next_90_days', :from => '', :to => ''})}, 'issue_status_id' => {:operator => 'o', :values => ['1']}, 'issue_is_planned' => {:operator => '=', :values => ['0']}, 'user_status'=>{:operator=>'=', :values => [User::STATUS_ACTIVE.to_s]} } end end
Spree::User.class_eval do # metodo que retorna true si es que esxiste acumulacion de despacho def has_delayed_dispatch? last_order = self.last_completed_order return 0 if last_order.nil? (last_order.completed_at.to_date + last_order.dispatch_days <=> Time.new.to_date) == 1 end #metodo para obtener los dias restantes de acumulación de despacho def calculate_delayed_dispactch_days last_order = self.last_completed_order return 0 if last_order.nil? days = (last_order.completed_at.to_date + last_order.dispatch_days - Time.new.to_date).to_i return days > 0 ? days : 0 end # para obtener la ultima orden completada def last_completed_order orders = self.orders.sort { |x,y| y.created_at <=> x.created_at } orders.each do |order| # if orders[last_index].paid? if order.completed? return order break end end return nil end def last_incomplete_spree_order spree_orders.incomplete.order('created_at DESC').first end end
# frozen_string_literal: true require 'test_helper' require 'rubyXL/address' class RubyXL::AddressTest < Minitest::Test def test_worksheet worksheet1 = 'dummy1' worksheet2 = 'dummy2' addr = RubyXL::Address.new(worksheet1, ref: :A1) assert_same worksheet1, addr.worksheet # #worksheet(value) creates an new Address. assert_same worksheet2, addr.worksheet(worksheet2).worksheet # #worksheet(value) does not change self. assert_same worksheet1, addr.worksheet end def test_worksheet_setter worksheet1 = 'dummy1' worksheet2 = 'dummy2' addr = RubyXL::Address.new(worksheet1, ref: :A1) addr.worksheet = worksheet2 assert_same worksheet2, addr.worksheet end def test_row addr = RubyXL::Address.new('dummy', row: 2, column: 1) assert_equal 2, addr.row # #row(value) creates an new Address. assert_equal 5, addr.row(5).row assert_equal 4, addr.row('5').row assert_equal 6, addr.row(:'7').row # #row(value) does not change column. assert_equal addr.column, addr.row(5).column # #row(value) does not change self. assert_equal 2, addr.row end def test_column addr = RubyXL::Address.new('dummy', row: 1, column: 2) assert_equal 2, addr.column # #column(value) creates an new Address. assert_equal 5, addr.column(5).column assert_equal 4, addr.column('E').column assert_equal 6, addr.column(:G).column # #column(value) does not change row. assert_equal addr.row, addr.column(5).row # #column(value) does not change self. assert_equal 2, addr.column end def test_row_setter addr = RubyXL::Address.new('dummy', ref: :A1) addr.row = 5 assert_equal 5, addr.row addr.row = '5' assert_equal 4, addr.row addr.row = :'7' assert_equal 6, addr.row end def test_column_setter addr = RubyXL::Address.new('dummy', ref: :A1) addr.column = 5 assert_equal 5, addr.column addr.column = 'E' assert_equal 4, addr.column addr.column = :G assert_equal 6, addr.column end def test_ref assert_equal 'A1', RubyXL::Address.new('dummy', ref: :A1).ref end def test_inspect worksheet = workbook.add_worksheet('TEST') assert_equal '#<RubyXL::Address TEST!A1>', RubyXL::Address.new(worksheet, ref: :A1).inspect end def test_up addr = RubyXL::Address.new('dummy', ref: :A9) assert_equal addr.row - 1, addr.up.row assert_equal addr.row - 0, addr.up(0).row assert_equal addr.row - 1, addr.up(1).row assert_equal addr.row - 3, addr.up(3).row assert_equal addr.row + 3, addr.up(-3).row assert_equal addr.column, addr.up.column end def test_up_error addr = RubyXL::Address.new('dummy', row: 0, column: 1) assert_raises(ArgumentError) { addr.up } end def test_down addr = RubyXL::Address.new('dummy', ref: :A9) assert_equal addr.row + 1, addr.down.row assert_equal addr.row + 0, addr.down(0).row assert_equal addr.row + 1, addr.down(1).row assert_equal addr.row + 3, addr.down(3).row assert_equal addr.row - 3, addr.down(-3).row assert_equal addr.column, addr.down.column end def test_left addr = RubyXL::Address.new('dummy', ref: :I1) assert_equal addr.column - 1, addr.left.column assert_equal addr.column - 0, addr.left(0).column assert_equal addr.column - 1, addr.left(1).column assert_equal addr.column - 3, addr.left(3).column assert_equal addr.column + 3, addr.left(-3).column assert_equal addr.row, addr.left.row end def test_left_error addr = RubyXL::Address.new('dummy', row: 1, column: 0) assert_raises(ArgumentError) { addr.left } end def test_right addr = RubyXL::Address.new('dummy', ref: :I1) assert_equal addr.column + 1, addr.right.column assert_equal addr.column + 0, addr.right(0).column assert_equal addr.column + 1, addr.right(1).column assert_equal addr.column + 3, addr.right(3).column assert_equal addr.column - 3, addr.right(-3).column assert_equal addr.row, addr.right.row end def test_up! addr = RubyXL::Address.new('dummy', ref: :A9) row = addr.row column = addr.column addr.up!(1) row -= 1 assert_equal row, addr.row addr.up!(0) assert_equal row, addr.row addr.up!(1) row -= 1 assert_equal row, addr.row addr.up!(3) row -= 3 assert_equal row, addr.row addr.up!(-3) row += 3 assert_equal row, addr.row # #up! does not change column. assert_equal column, addr.column end def test_up_error! addr = RubyXL::Address.new('dummy', row: 0, column: 1) assert_raises(ArgumentError) { addr.up! } end def test_down! addr = RubyXL::Address.new('dummy', ref: :A9) row = addr.row column = addr.column addr.down!(1) row += 1 assert_equal row, addr.row addr.down!(0) assert_equal row, addr.row addr.down!(1) row += 1 assert_equal row, addr.row addr.down!(3) row += 3 assert_equal row, addr.row addr.down!(-3) row -= 3 assert_equal row, addr.row # #down! does not change column. assert_equal column, addr.column end def test_left! addr = RubyXL::Address.new('dummy', ref: :I1) row = addr.row column = addr.column addr.left!(1) column -= 1 assert_equal column, addr.column addr.left!(0) assert_equal column, addr.column addr.left!(1) column -= 1 assert_equal column, addr.column addr.left!(3) column -= 3 assert_equal column, addr.column addr.left!(-3) column += 3 assert_equal column, addr.column # #left! does not change row. assert_equal row, addr.row end def test_left_error! addr = RubyXL::Address.new('dummy', row: 1, column: 0) assert_raises(ArgumentError) { addr.left! } end def test_right! addr = RubyXL::Address.new('dummy', ref: :I1) row = addr.row column = addr.column addr.right!(1) column += 1 assert_equal column, addr.column addr.right!(0) assert_equal column, addr.column addr.right!(1) column += 1 assert_equal column, addr.column addr.right!(3) column += 3 assert_equal column, addr.column addr.right!(-3) column -= 3 assert_equal column, addr.column # #right! does not change row. assert_equal row, addr.row end def test_cell addr = RubyXL::Address.new(worksheet, ref: :A9) assert_nil addr.cell worksheet.add_cell(addr.row, addr.column) assert_same worksheet[addr.row][addr.column], addr.cell end def test_value addr = RubyXL::Address.new(worksheet, ref: :C7) assert_nil addr.value worksheet.add_cell(addr.row, addr.column, 'foobar') assert_same worksheet[addr.row][addr.column].value, addr.value end def test_value_setter addr = RubyXL::Address.new(worksheet, ref: :D6) assert_nil addr.cell value = 'foo' addr.value = value assert_same value, worksheet[addr.row][addr.column].value value = 'baz' addr.value = value assert_same value, worksheet[addr.row][addr.column].value addr = RubyXL::Address.new(worksheet, ref: :E5) assert_nil addr.cell value = true addr.value = value assert_same value, worksheet[addr.row][addr.column].value end private def workbook @@workbook ||= begin require 'rubyXL' RubyXL::Workbook.new end end def worksheet @@worksheet ||= workbook[0] end end
def turn_count(board) #initializes our counter to 0 counter = 0 # iterate over board array and save values in turn variable board.each do |turn| #condition for iteration if turn == "X" || turn == "O" counter += 1 end end # return counter return counter end def current_player(board) if turn_count(board) % 2 == 0 return "X" else return "O" end end
FactoryGirl.define do factory :next_of_kin do name "MyString" relationship "MyString" phonenumber "MyString" address "MyString" employee nil end end
class GamesController < ApplicationController before_action :set_thing, only: [:show, :edit, :update, :destroy, :gamtus_maker, :toggle_status] before_action :set_gamtus, only: [:show, :toggle_wishlist, :toggle_owned, :toggle_beaten, :toggle_completed] access all: [:index, :show], user: {except: [:destroy, :new, :create, :update, :edit]}, admin: :all def index q_param = params[:q] page = params[:page] @q = Game.published.ransack q_param @games = @q.result.page(page).per(10) end def new @game = Game.new @game.game_gallaries.build end def create @game = Game.new(games_params) searchable if @game.save redirect_to games_path else render :new end end def show @chargams = CharactersGame.where(game_id: @game.id) @characters = Character.all @gamplats = Gamplat.where(game_id: @game.id) @gamples = Gample.where(game_id: @game.id) @platforms = Platform.all @peoples = Person.all end def edit end def update if @game.update(games_params) searchable @game.save redirect_to @game else render :edit end end def destroy if @game.destroy redirect_to games_path, notice: 'Your post was edited successfully' else render :show, notice: 'Your edit failed' end end def toggle_status if @game.draft? @game.published! elsif @game.published? @game.draft! end redirect_to user_dashboard_admin_path, notice: "#{@game.title} status has been updated." end def toggle_wishlist gamtus_maker @gamtus.update(status: 'wishlist') redirect_to game_path, notice: 'game has been added to your wishlist' end def toggle_owned gamtus_maker @gamtus.update(status: 'owned') redirect_to game_path, notice: 'game has been added to your owned list' end def toggle_beaten gamtus_maker @gamtus.update(status: 'beaten') redirect_to game_path, notice: 'game has been added to your beaten list' end def toggle_completed gamtus_maker @gamtus.update(status: 'completed') redirect_to game_path, notice: 'game has been added to your completed list' end private def games_params params.require(:game).permit( :title, :description, :release, :main_image, game_gallaries_attributes: [ :id, :title, :image, :_destroy], gamplats_attributes: [:id, :platform_id, :_destroy]) end def set_thing @game = Game.find(params[:id]) end def searchable @game.searchable = @game.title + @game.release.to_s + @game.description end def set_gamtus set_thing if user_signed_in? @gamtus = UserGameStatus.find_by user_id: current_user.id, game_id: @game.id end end def gamtus_maker if @gamtus == nil @gamtus = UserGameStatus.create(user_id: current_user.id, game_id: @game.id) end end end
require 'csv' class LoadAccountantsJob < ApplicationJob queue_as :default def perform csv_options = { col_sep: ',', quote_char: '"', headers: :first_row } filepath = 'db/accountants.csv' CSV.foreach(filepath, csv_options) do |row| Accountant.create!(name: row['name'], email: row['email'], phone_number: row['phone_number'], website: row['website'], qualification: row['qualification'], location: row['location'], industries_string: row['industries']) end end end # Run: # rails c # LoadAccountantsJob.perform_now
FactoryGirl.define do factory :claims_checklist, :class => Refinery::ClaimsChecklists::ClaimsChecklist do sequence(:checklist_name) { |n| "refinery#{n}" } end end
class HomeController < ApplicationController def index @food = Food.where(kind: "fruit") end end
module Mastermind class Player attr_accessor :guesses, :score, :wins, :losses, :points, :guess_size, :min_digit, :max_digit :valid attr_reader :max_guesses, :valid, :code_size, :min_digit, :max_digit def initialize(code_size, min_digit, max_digit) @guesses = [] @score = 0 @wins = 0 @losses = 0 @points = 0 @guess_size = code_size @min_digit = min_digit @max_digit = max_digit @max_guesses = 6 @valid = Validate.new(@max_guesses) end def set_guess(guess, code) status = "" guess_digit = guess.split("") code_digit = code.split("") guess_digit.size.times do |x| status << ((guess_digit[x] == code_digit[x]) ? guess_digit[x] : "x") end @guesses << status end # -- Score Keeping ------------------------------------ def update_score(w, l, p) @wins = @wins + w @losses = @losses + l @points = @points + p end # -- AI Player ---------------------------------------- def get_random_digit digit = rand(@max_digit) + 1 ((@min_digit..@max_digit) === digit) ? digit : get_random_digit end def make_first_guess (@min_digit..@guess_size).map { rand(@max_digit) + 1 }.join end def make_guess store = "" compare = @guesses.last.split("") while store.size < @guess_size check = compare[store.size] store << ((@valid.entry?(check)) ? check.to_s : get_random_digit.to_s) end store end def generate_code (@min_digit..@guess_size).map { rand(@max_digit) + 1 }.join end def generate_guess store = (@guesses == []) ? make_first_guess : make_guess end def exhaust_guesses(code) while @guesses.size < @max_guesses set_guess(generate_guess, code) if @valid.entry?(@guesses.last) break end end end end end
class Month < Periode has_many :weeks def periode_names periodes = [] self.weeks.each do |periode| periodes << periode.id periodes += periode.periode_names end periodes end end
json.array! @new_messages do |message| json.body message.body json.image message.image.url json.name message.user.name json.created_at shape_create_time(message.created_at) json.id message.id end
require File.dirname(__FILE__) + '/../lib/migration_runner' DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/migration_test.db") DataMapper::Logger.new(STDOUT, :debug) DataMapper.logger.debug( "Starting Migration" ) migration 1, :create_people_table do up do create_table :people do column :id, :int, :primary_key => true column :name, :string column :age, :int end end down do drop_table :people end end
require 'ruble' bundle do |bundle| bundle.display_name = t(:bundle_name) bundle.author = 'Joost de Valk, Brett Terpstra' bundle.description = <<END Wordpress Ruble converted from TextMate bundle. TM Bundle by: http://yoast.com/tools/textmate/ - Joost de Valk http://blog.circlesixdesign.com/ - Brett Terpstra END bundle.repository = 'git://github.com/aptana/wordpress.ruble.git' bundle.menu t(:bundle_name) do |main_menu| main_menu.menu t(:structure) do |submenu| submenu.command t(:sidebar) submenu.command t(:comments) submenu.command t(:html_body_tag) submenu.command t(:footer) submenu.command t(:header) end main_menu.menu t(:loop) do |submenu| submenu.command t(:comment) submenu.command t(:author_meta) submenu.command t(:loop) submenu.command t(:headline) submenu.separator submenu.command t(:post) submenu.command t(:navigation) submenu.separator submenu.command t(:query_posts) submenu.command t(:flush_query_cache) submenu.command t(:insert_class_reference) submenu.command t(:insert_table_reference) submenu.command t(:insert_row_reference) submenu.separator submenu.command t(:insert_constant) submenu.command t(:insert_condition) submenu.separator submenu.command t(:bloginfo_general) submenu.command t(:bloginfo_feeds) #submenu.menu 'Navigation' do |submenu| #end end main_menu.menu t(:categories) do |submenu| submenu.command t(:list_categories_wp) submenu.command t(:list_categories_full_options) submenu.command t(:get_category_parents) submenu.command t(:get_category) submenu.command t(:cat_member_variable) end main_menu.menu t(:plugins) do |submenu| submenu.command t(:filter) submenu.command t(:action) end main_menu.menu t(:other) do |submenu| submenu.command t(:escaping_functions) submenu.command t(:single_post_title) submenu.command t(:post_member_variable) submenu.command t(:comment_member_variable) submenu.command t(:get_archives) submenu.command t(:wp_redirect) submenu.command t(:link) end main_menu.menu t(:plugin_creation) do |submenu| submenu.command t(:widget) submenu.command t(:readme_txt) submenu.command t(:plugin_with_gpl) submenu.command t(:plugin) end main_menu.menu t(:localization) do |submenu| submenu.command t(:localize) submenu.command t(:localize_var) end end end
Rails.application.routes.draw do root 'questions#index' get '/questions/:index', to: 'questions#show' end
Pod::Spec.new do |s| s.name = 'WVRNetModel' s.version = '0.0.4' s.summary = 'WVRNetModel files' s.homepage = 'http://git.moretv.cn/whaley-vr-ios-lib/WVRNetModel' s.license = 'MIT' s.authors = {'whaleyvr' => 'vr-iosdev@whaley.cn'} s.platform = :ios, '9.0' s.source = {:git => 'http://git.moretv.cn/whaley-vr-ios-lib/WVRNetModel.git', :tag => s.version} s.source_files = 'WVRNetModel/Classes/*.{h,m}' s.requires_arc = true s.dependency 'YYModel' s.dependency 'LKDBHelper' s.dependency 'WVRUtil' end
class ProductsUsersController < ApplicationController before_filter :require_session before_filter :find_product def create @products_user = ProductsUser.create!(product: @product, user: current_user) flash[:success] = "#{@product.name} successfully added to cart" redirect_to products_path end private def find_product @product = Product.find(params[:product_id]) end end
require 'rails_helper' RSpec.describe OpinionsController, type: :controller do describe '#rate' do it 'creates a rating' do skatepark = create(:skatepark) user = create(:user) rating = 5 post :rate, skatepark_id: skatepark.id, user_id: user.id, rating: rating expect(Rating.last.skatepark_id).to eq(skatepark.id) expect(Rating.last.user_id).to eq(user.id) expect(Rating.last.rating).to eq(rating) end end describe '#review' do it 'creates a review' do skatepark = create(:skatepark) user = create(:user) review = "This is really a fabulous scene. But it still sucks" post :review, skatepark_id: skatepark.id, user_id: user.id, review: review expect(Review.last.skatepark_id).to eq(skatepark.id) expect(Review.last.user_id).to eq(user.id) expect(Review.last.review).to eq(review) end end end
class Review < ActiveRecord::Base belongs_to :user belongs_to :item has_many :votes validates :rating, presence: true, numericality: true, inclusion: { in: 1..5, message: 'must be between 1-5' } RATING_OPTIONS = [ ["Pick a Rating".freeze, 0], ["5 - Amazing".freeze, 5], ["4 - Great".freeze, 4], ["3 - Mediocre".freeze, 3], ["2 - Bad".freeze, 2], ["1 - Awful".freeze, 1] ].freeze def net_rating votes.inject(0) { |sum, vote| sum + vote.score } end end
class Bill < ActiveRecord::Base attr_accessible :amount, :bill_date, :payer, :store has_many :debtors end
module GChart class Map < GChart::Base AREAS = %w[africa asia europe middle_east south_america usa world] attr_accessor :area attr_accessor :area_codes attr_accessor :background def initialize(*args, &block) super(*args, &block) # Set some sane defaults so that the only requirement is data @area = 'world' #default @background = 'dfdfff' #make it look like water @colors = ['ffffff','f8fcf8','006c00'] #Set the maximum size for maps (this is a better default because # it is also the proper aspect ratio) @width = '440' @height = '220' end # Map data can be in the form {"VA'=>5,'NY'=>1} or [['VA',5],['NY',1]] # Raises +ArgumentError+ if data does not fit these forms. def data=(data) if data.is_a?(Array) && data.any?{ |pair| pair.size != 2 } raise ArgumentError, "Data array must contain [area],[value] pairs" end # 'unzip' the data into separate arrays area_data, values = data.to_a.transpose # Reject malformed area codes if area_data.any?{ |code| code !~ /^\w\w$/} raise ArgumentError, "Area data must have exactly two characters" end @area_codes = area_data.join.upcase super(values) end def render_chart_type #:nodoc: "t" end def area=(area) raise ArgumentError unless AREAS.include? area @area = area end # overrides GChart::Base#query_params def query_params(params={}) #:nodoc: params["chtm"] = area unless area.empty? params["chld"] = area_codes if area_codes params["chf"] = "bg,s,#{@background}" if @background super(params) end # overrides GChart::Base#render_data def render_data(params) super(params) # Maps require at least one data point. Add a "missing value". # It may be better to refactor the base class. params["chd"] << '__' if params["chd"] =~ /e:$/ end def render_title(params) #:nodoc: nil #N/A for map end def render_legend(params) #:nodoc: nil #N/A for map end end end
FactoryGirl.define do factory :warehouse do city "DaMOON" location_code {"#{city.upcase[0..2]}-#{rand(10000..99999).to_s}"} end end
# Install Java, Tomcat and Solr %w(openjdk-6-jre-headless solr-tomcat).each do |app| package app do action :install end end # Copy the Solr config files from the cookbook's files directory %w(schema.xml solrconfig.xml).each do |config_file| cookbook_file "/etc/solr/conf/#{config_file}" do source config_file mode "0644" notifies :restart, "service[tomcat6]" end end # Make sure the tomcat6 user can write to /var/lib/tomcat6 directory "/var/lib/tomcat6" do owner 'tomcat6' group 'tomcat6' mode '0744' end service "tomcat6"
# frozen_string_literal: true # Configure Rails Environment ENV["RAILS_ENV"] = "test" require_relative "../test/dummy/config/environment" require_relative 'slack_test_helper' require "rails/test_help" require 'mocha/minitest' require 'byebug' # Filter out Minitest backtrace while allowing backtrace from other libraries # to be shown. Minitest.backtrace_filter = Minitest::BacktraceFilter.new module ActiveSupport class TestCase # returns a tuple of found_logs (Array), and result (whatever the block returns) def assert_log_message(log_level, logger: Rails.logger, regexp: nil, message: nil, &block) add_log_expectation(log_level, logger: logger, run_assertion: true, regexp: regexp, message: message, &block) end # returns a tuple of found_logs (Array), and result (whatever the block returns) def refute_log_message(log_level, logger: Rails.logger, regexp: nil, message: nil, &block) add_log_expectation(log_level, logger: logger, run_assertion: false, regexp: regexp, message: message, &block) end def add_log_expectation(log_level, logger:, run_assertion: true, regexp: nil, message: nil) found_lines = [] all_lines = [] logger.expects(log_level).with do |line| if (regexp && line =~ regexp) || (line == message) found_lines << line if line.present? end all_lines << line if line.present? true end.at_least(0) result = yield if run_assertion message = "Expected log #{log_level} not found with message: \n#{regexp || message}\n" if all_lines.empty? message += "No logs found." else message += "Logs found:\n" message += "=============\n" message += all_lines.join("\$\n") message += "\n=============\n\n" end assert(found_lines.present?, message: message) else message = "Expected to not log #{log_level} with message \n'#{regexp || message}' but it was logged.\n" if found_lines.present? message += "Logs found:\n" message += "=============\n" message += found_lines.join("\$\n") message += "\n=============\n\n" end assert(found_lines.blank?, message: message) end [found_lines, result] end end end
require 'rails_helper' RSpec.describe 'Registrations', type: :request do describe 'POST /registrations' do let(:params) do { email: 'user@example.com', password: 'password1' } end subject { post registrations_path, params: params } it { is_expected.to eq 201 } context 'with invalid params' do let(:params) { nil } it { is_expected.to eq 422 } end end end
# API for showing the user's calendar with iCal class CalendarsController < ApplicationController before_action :basic_auth_user, if: :ical? before_action :require_user def show @calendar = current_user.calendar expires_in 30.minutes, public: true end private def basic_auth_user authenticate_or_request_with_http_basic t(:name) do |id, token| self.current_user = User.find_by(facebook_id: id, token: token) logger.info "Authenticated user #{current_user.email} from basic auth" end end def require_user if current_user.blank? redirect_to root_path return end end def ical? request.format == :ics end end
class MiscMailer < ActionMailer::Base # Use application_mail.html.erb layout 'application_mailer' # Automatically inject css styles include Roadie::Rails::Mailer default to: "bennettlee908@gmail.com" # Mail when user contacts Lendojo staff def contact(params) @name = params[:name] @category = params[:category] #General Questions, Technical Questions, Suggestions, Business Inquiries, Media, Other to = "bennettlee908@gmail.com" from = @name + "<" + params[:email_from] + ">" @message = params[:message] mail(to: to, from: from, subject: 'Lenodjo: Contact') do |format| format.html { render 'contact' } end end end
class UsersController < ApplicationController before_action :authenticate_user! after_action :verify_authorized def index @users = User.all authorize @users end def show @user = params[:id].blank? ? current_user : User.find(params[:id]) authorize @user end def edit @user = params[:id].blank? ? current_user : User.find(params[:id]) authorize @user end def update @user = params[:id].blank? ? current_user : User.find(params[:id]) authorize @user if @user.update_attributes(user_params) render json: @user.as_json else render json: { errors: @user.errors } end end def destroy @user = User.find(params[:id]) authorize @user @user.destroy redirect_to users_path end private def user_params params.require(:project).permit(:name, :email) end end
class PranksController < ApplicationController skip_before_action :authenticate_user!, only: [:index, :show] def index @pranks = if params[:query] policy_scope(Prank).search_by_name_content_city(params[:query]) else policy_scope(Prank) end end def show @booking = Booking.new @prank = Prank.find(params[:id]) authorize @prank end def new @prank = Prank.new @prank.user = current_user authorize @prank end def create @prank = Prank.create(prank_params) @prank.user = current_user authorize @prank if @prank.save redirect_to prank_path(@prank) else render :new end end def prank_params params.require(:prank).permit(:name, :content, :price, :city, :photo) end end
class PracticasController < AuthorizedController respond_to :html, :only => [:index, :show, :new, :edit] before_filter :get_practice, :only => [:show, :edit, :lab, :make_practice, :messages, :finished] include CustomFayeSender def index @practicas = Practica.all end def show end def messages get_messages end def new @practica = Practica.new @dispositivos = Dispositivo.all @dispositivos_reservados = [] @allowed_users = [] #ap @practica.event.start #ap @practica.event.end end def edit end def create @practica = Practica.new(params[:practica]) @dispositivos = Dispositivo.all @dispositivos_reservados = [] @allowed_users = [] @show_first = false @practica.users << current_user respond_to do |format| if @practica.save format.html { redirect_to(@practica, :notice => 'Practica was successfully created.') } else format.html { render :action => "new" } end end end def update params[:practica][:dispositivo_ids] ||= [] @practica = Practica.find(params[:id]) respond_to do |format| if @practica.update_attributes(params[:practica]) @practica.users << current_user unless (@practica.users.include? current_user) format.html { redirect_to(@practica, :notice => 'Practica was successfully updated.') } else format.html { render :action => "edit" } end end end def update_diagram @practica = Practica.find(params[:id]) @success = true valid_params = params.select {|k,v| [:image, :remote_image_url].include? k} respond_to do |format| if @practica.update_attributes(valid_params) else @success = false end format.js end end def destroy @practica.destroy respond_to do |format| format.html { redirect_to(practicas_url) } end end def finished get_messages end def make_practice if (!current_user.is_a? Admin) && @practica.cerrada? respond_to do |format| format.html { redirect_to(finished_practica_path(@practica), :alert => 'This Practica is closed!') } end end channel_sym = "practica_#{@practica.id}".to_sym if current_user.options[:faye][channel_sym].nil? current_user.options[:faye][channel_sym] = :available if current_user.save broadcast_chat_status channel_sym, :available end else broadcast_chat_status channel_sym, current_user.options[:faye][channel_sym] end @channel = channel_sym @logical_connections = Vlan.where(:practica_id >> @practica.id) @conexion = Vlan.new @puertos = [] @dispositivos_reservados.each do |dispositivo| @puertos += dispositivo.puertos end @puertos = @puertos.uniq # See which vlans exist #@practica.vlans.each do |vlan| # p1 = vlan.puerto # p2 = vlan.endpoint # @puertos.delete_if {|un_puerto| (un_puerto.id == p1.id || un_puerto.id == p2.id)} #end @puertos.collect! do |p| if p.dispositivo ["#{p.dispositivo.nombre} - #{p.etiqueta}",p.id] else ["N/A - #{p.etiqueta}",p.id] end end end def terminal @mensaje = {} @mensaje[:message] = params[:message][:content] # Filter non-permitted commands and log, whatever we want unless @mensaje[:message].empty? @mensaje[:message] = @mensaje[:message].gsub('#SLASH','/') # TODO: fix this thing... @mensaje[:message] = @mensaje[:message] == "reload" ? "" : @mensaje[:message] # Send through faye first to provide echo @mensaje[:channel] = params[:message][:channel] # Set echo to true if sending to himself via faye is required @mensaje[:echo] = false if current_user @mensaje[:user] = current_user.username else @mensaje[:user] = 'unregistered_user' end mensaje_raw = FayeMessagesController.new.generate_terminal_user_output @mensaje send_via_faye "#{FAYE_CHANNEL_PREFIX}#{@mensaje[:channel]}", mensaje_raw # Send through RemoteIRCGateway... RemoteIRCGateway.instance.send_irc("##{@mensaje[:channel]}", @mensaje[:message]) #Add to record of messages the_message = Message.new(:content => @mensaje[:message], :practica_id => @practica.id, :dispositivo_id => @mensaje[:channel].split('_').last, :user_id => current_user.id) if the_message.save puts "DEBUG-Se guardo el mensaje #{the_message.attributes}" else puts "No se pudo guardar el mensaje #{the_message.errors.full_messages.to_sentence}" end end render :nothing => true end # Generates JS for practica def lab @faye_channels = @dispositivos_reservados.map do |dispositivo| "#{FAYE_CHANNEL_PREFIX}device_#{dispositivo.id}" end @faye_channels << "#{FAYE_CHANNEL_PREFIX}practica_#{@practica.id}" @faye_server_url = FAYE_SERVER_URL if current_user @username = current_user.username @user_id = current_user.id else @username = '_non_reg' @user_id = -1 end @puertos = [] @dispositivos_reservados.each do |dispositivo| @puertos += dispositivo.puertos end @puertos = @puertos.uniq #See which vlans exist @practica.vlans.each do |vlan| p1 = vlan.puerto p2 = vlan.endpoint @puertos.each do |un_puerto| (un_puerto.id == p1.id || un_puerto.id == p2.id) ? un_puerto.runtime_state = :conectado : un_puerto.runtime_state = :libre end end respond_to do |format| format.js end end def chat @mensaje = {} @mensaje[:message] = params[:message][:content] # Filter non-permitted commands and log, whatever we want if not @mensaje[:message].empty? # Send through faye first to provide echo @mensaje[:channel] = params[:message][:channel] # Set echo to true if sending to himself via faye is required @mensaje[:echo] = false if current_user @mensaje[:user] = current_user.username else @mensaje[:user] = '_non_reg' end mensaje_raw = FayeMessagesController.new.generate_chat_output @mensaje send_via_faye "#{FAYE_CHANNEL_PREFIX}#{@mensaje[:channel]}", mensaje_raw end render :nothing => true end def chat_status channel = "practica_#{params[:id]}" status = params[:status] if status.eql? 'offline' current_user.options[:faye].delete channel.to_sym else current_user.options[:faye][(channel.to_sym)] = status.to_sym end if current_user.save broadcast_chat_status channel, status render :nothing => true else render :status => 500 end end def new_conexion the_practica = Practica.find(params[:id]) the_vlan = Vlan.new(params[:vlan]) the_vlan.practica = the_practica #puts "DEBUG ##################3 practica is #{the_practica.inspect}" # #the_vlan = puerto.conectar_logicamente endpoint # #puts "DEBUG ##################3 the_vlan is #{the_vlan.inspect}" channel = "practica_#{the_practica.id}" if the_vlan.save RemoteIRCGateway.instance.create_vlan the_vlan mensaje_raw = FayeMessagesController.new.generate_new_conexion_output the_vlan send_via_faye "#{FAYE_CHANNEL_PREFIX}#{channel}", mensaje_raw else mensaje_raw = FayeMessagesController.new.generate_new_conexion_error_output the_vlan send_via_faye "#{FAYE_CHANNEL_PREFIX}#{channel}", mensaje_raw end render :nothing => true end def remove_conexion the_vlan = Vlan.find(params[:con_id]) channel = "practica_#{params[:id]}" if (RemoteIRCGateway.instance.remove_vlan the_vlan).class.eql? Net::HTTPOK mensaje_raw = FayeMessagesController.new.generate_remove_conexion_output the_vlan send_via_faye "#{FAYE_CHANNEL_PREFIX}#{channel}", mensaje_raw end render :nothing => true end # TODO: See what this method is for - not used def practice_events @practice_events = Practica.where("name like ?", "%#{params[:q]}%") respond_to do |format| format.json { render :json => @practice_events.collect { |event| {:title => event.name, :start => event.start, :end => event.end} } } end end def free_devices _start = DateTime.parse params[:start] _end = DateTime.parse params[:end] events = Event.where(((:start >= _start) & (:end <= _end)) | ((:start < _start) & (:end > _start)) | ((:start < _end) & (:end > _end)) | ((:start <= _start) & (:end >= _end))) events.map!{|event| event.eventable} filtered_practices = events.select{|eventable| eventable.is_a? Practica} #filtered_practices = Practica.exist_in_span(_start, _end) reserved_devices = [] filtered_practices.each do |practica| reserved_devices += practica.dispositivos end reserved_devices = reserved_devices.uniq @dispositivos = Dispositivo.for_users.ok @free_devices = @dispositivos - reserved_devices end # THIS IS PRIVATE !!! private # Get practica, associated users and devices def get_practice @practica = Practica.find(params[:id], :include => [:users, :dispositivos]) @dispositivos_reservados = @practica.dispositivos @allowed_users = @practica.users end # Broadcast this user's chat status in a specific channel def broadcast_chat_status(channel, status) mensaje_raw = FayeMessagesController.new.generate_chat_status_output current_user, status send_via_faye "#{FAYE_CHANNEL_PREFIX}#{channel}", mensaje_raw end def get_messages messages_by_device_id = @practica.messages.all.group_by(&:dispositivo_id) messages_by_device_id messages_by_device_array = messages_by_device_id.map do |device_id, messages| [Dispositivo.find(device_id), messages] end @messages_by_device = Hash[messages_by_device_array] end end
require "application_system_test_case" class PetsTest < ApplicationSystemTestCase setup do @pet = pets(:one) end test "visiting the index" do visit pets_url assert_selector "h1", text: "Pets" end test "creating a Pet" do visit pets_url click_on "New Pet" fill_in "Birth", with: @pet.birth fill_in "Breed", with: @pet.breed fill_in "Kind", with: @pet.kind_id fill_in "Name", with: @pet.name fill_in "Owner", with: @pet.owner_id click_on "Create Pet" assert_text "Pet was successfully created" click_on "Back" end test "updating a Pet" do visit pets_url click_on "Edit", match: :first fill_in "Birth", with: @pet.birth fill_in "Breed", with: @pet.breed fill_in "Kind", with: @pet.kind_id fill_in "Name", with: @pet.name fill_in "Owner", with: @pet.owner_id click_on "Update Pet" assert_text "Pet was successfully updated" click_on "Back" end test "destroying a Pet" do visit pets_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Pet was successfully destroyed" end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "MattHodge/Windows2016StdCore-WMF5-NOCM" config.vm.provider "virtualbox" do |vb| vb.gui = true vb.memory = "6144" vb.linked_clone = true end config.vm.provider "hyperv" do |hv| # hyperv provisioner doesn't name things nicey randy = rand(10000) hv.vmname = "Windows2016StdCore-WMF5-NOCM" + randy.to_s hv.cpus = 1 hv.memory = 6144 hv.differencing_disk = true hv.enable_virtualization_extensions = true end config.vm.provision "shell", path: "install_tc_build_agent.ps1", env: {"TEAMCITY_HOST_URL" => ENV['TEAMCITY_HOST_URL']} config.vm.synced_folder ".", "/vagrant", disabled: true end
module SentimentHelper def analyze(text) uri = URI('https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment') request = Net::HTTP::Post.new(uri.request_uri) # Request headers request['Content-Type'] = 'application/json' # Request headers request['Ocp-Apim-Subscription-Key'] = ENV["MICROSOFT_KEY"] # Request body request.body = { "documents": [ { "language": "en", "id": "string", "text": text } ] }.to_json response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| http.request(request) end end def get_emotions(analysis) # breakdown into 10 different emotional indicators score = JSON.parse(analysis.body)["documents"][0]["score"] if score < 0.33 'sad' elsif score < 0.66 'ok' else 'happy' end end end
atom_feed do |feed| feed.title "A Porter's Tale" feed.updated(@comics[0].created_at) if @comics.length > 0 @comics.each do |comic| feed.entry(comic) do |entry| entry.title(comic.title) entry.content(comic.description) entry.tag!('app:edited', Time.now) entry.author do |author| author.name("A Porter's Tale") end end end end
class NonUserParticipant < ApplicationRecord belongs_to :study validates :study_id, :recruitment_date, presence: true end
class Reply include Mongoid::Document include Mongoid::Timestamps field :body, type: String, default: "" belongs_to :post validates_presence_of :post after_create do post.inc(:replies_count => 1) end belongs_to :author, class_name: "User" end
require 'sinatra' # Class for route /accounts/authenticate class FileSystemSyncAPI < Sinatra::Base post '/accounts/authenticate' do content_type 'application/json' begin credentials = JSON.parse(request.body.read, :symbolize_names => true) authenticated = AuthenticateAccount.call(credentials) rescue => e logger.info "Cannot authenticate #{credentials['username']}: #{e}" halt 500 end authenticated ? authenticated.to_json : status(403) end end
class ActivitiesController < ApplicationController include ActivitiesHelper def new @activity = Activity.new @trip = params[:id] end def create new_activity = Activity.create(activity_params) validate(new_activity) trip = params[:id] add_trip = current_user.trips.find(trip) add_trip.activities << new_activity flash[:success] = "#{new_activity.name} has been added!" redirect_to trip_path(trip) end def add_activity session[:return_to] ||= request.referer new_activity = Activity.create(activity_params) validate(new_activity) trip = params[:id] add_trip = current_user.trips.find(trip) add_trip.activities << new_activity flash[:success] = "#{new_activity.name} has been added!" redirect_to session.delete(:return_to) end def edit id = params[:activity_id] @activity = Activity.find(id) end def update id = params[:activity_id] trip = params[:id] activity = Activity.find(id) activity.update(activity_params) flash[:success] = "#{activity.name} has been udpated!" redirect_to trip_path(trip) end def show id = params[:activity_id] @trip = params[:id] @activity = Activity.find(id) end def destroy id = params[:activity_id] trip = params[:id] Activity.find(id).destroy flash[:success] = "Activity has been deleted" redirect_to trip_path(trip) end private def activity_params params.require(:activity).permit(:name, :address, :thumbnail_photo, :biz_url, :phone, :yid, :rating) end end
require "test_helper" describe ProductsController do CATEGORIES = %w(air tropical succulents cacti herbs trees planters) INVALID_CATEGORIES = ["nope", "42", "", " ", "Succulentstrailingtext"] describe "index" do it "succeeds for a real category with many products" do CATEGORIES.each do |category| Product.where(category: category).count.must_be :>, 0, "No #{category.pluralize} in the test fixtures" get products_path(category) must_respond_with :success end end it "succeeds for a real category with no products" do Product.destroy_all CATEGORIES.each do |category| get products_path must_respond_with :success end end # case for no category => products list # case for fake category end describe "show" do it "shows a product that exists" do product = Product.last get product_path(product) must_respond_with :success end end describe "create" do it "adds a product to the database" do product_data = { product: { name: "Orchid", price: 25.99, category: "Exotic", description: "text here", inventory: 120, photo_url: "link", merchant_id: Merchant.first.id } } post products_path, params: product_data must_redirect_to merchants_path end # it "re-renders the new product form if the product is invalid" do # product_data = { # product: { # name: "Orchid", # price: 25.99, # category: "Exotic" # } # } # post products_path, params: product_data # must_respond_with :bad_request # end end # describe "new" do # it "should get new" do # get new_product_path # value(response).must_be :success? # end describe "edit" do it "succeeds for an existent product ID" do get edit_product_path(Product.first) must_respond_with :success end it "renders 404 for a bogus product ID" do bogus_product_id = Product.last.id + 1 get edit_product_path(bogus_product_id) must_respond_with :not_found end end describe "update" do it "succeeds for valid data and an extant work ID" do product = Product.first product_data = { product: { name: product.name + " addition" } } patch product_path(product), params: product_data must_redirect_to products_path(product) Product.find(product.id).name.must_equal product_data[:product][:name] end it "renders bad_request for bogus data" do product = Product.first product_data = { product: { name: "" } } patch product_path(product), params: product_data must_respond_with :bad_request # Verify the DB was not modified Product.find(product.id).name.must_equal product.name end it "renders 404 not_found for a bogus product ID" do bogus_product_id = Product.last.id + 1 get product_path(bogus_product_id) must_respond_with :not_found end end # describe "destroy" do # it "succeeds for an extant product ID" do # product_id = Product.first.id # # delete product_path(product_id) # must_redirect_to root_path # # # The work should really be gone # Product.find_by(id: product_id).must_be_nil # end # # it "renders 404 not_found and does not update the DB for a bogus work ID" do # start_count = Product.count # # bogus_product_id = Product.last.id + 1 # delete product_path(bogus_product_id) # must_respond_with :not_found # # Product.count.must_equal start_count # end # end end
# frozen_string_literal: true # # Copyright (c) 2019-present, Blue Marble Payroll, LLC # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # module Proforma class HtmlRenderer # This class can render ERB templates. class Writer # This nested class is an internal intermediate only used by the encapsulating Writer class. # It is simply used to convert an OpenStruct object to a Binding object which can be used # for ERB template rendering. class ErbBinding < OpenStruct def expose_binding binding end end BACK_DIR = '..' ERB_OPTIONS = '-' TEMPLATE_DIR = 'templates' def initialize(directory: nil, files: {}) @directory = directory || default_directory @files = to_erb_hash(files) end def render(name, context = {}) erb_template(name).result(hash_to_binding(context)) end private attr_reader :directory, :files def hash_to_binding(hash) ErbBinding.new(hash).expose_binding end def erb_template(name) files[name.to_s] ||= read(name) end def read(name) text = IO.read(path(name)).chop ERB.new(text, nil, ERB_OPTIONS) end def default_directory File.join( __dir__, BACK_DIR, BACK_DIR, BACK_DIR, TEMPLATE_DIR ) end def path(name) File.join(directory, name.to_s) end def to_erb_hash(hash) (hash || {}).map do |(name, file)| [ name.to_s, file.is_a?(ERB) ? file : ERB.new(file) ] end.to_h end end end end
require_relative '../../../puppet_x/century_link/clc' require_relative '../../../puppet_x/century_link/prefetch_error' Puppet::Type.type(:clc_network).provide(:v2, parent: PuppetX::CenturyLink::Clc) do mk_resource_methods read_only(:id) def self.instances begin networks = client.list_networks networks.map { |network| new(network_to_hash(network)) } rescue Timeout::Error, StandardError => e raise PuppetX::CenturyLink::PrefetchError.new(self.resource_type.name.to_s, e) end end def self.prefetch(resources) instances.each do |prov| if resource = resources[prov.name] resource.provider = prov if resource[:datacenter].downcase == prov.datacenter.downcase end end end def self.network_to_hash(network) { id: network['id'], name: network['name'], description: network['description'], datacenter: network['datacenter'], ensure: :present, } end def exists? Puppet.info("Checking if network #{name} exists") @property_hash[:ensure] == :present end def create Puppet.info("Creating network #{name}") fail("datacenter can't be blank") if resource[:datacenter].nil? params = { 'name' => name, 'description' => resource[:description] } network = client.claim_network(resource[:datacenter]) client.update_network(resource[:datacenter], network['id'], remove_null_values(params)) @property_hash[:id] = network['id'] @property_hash[:ensure] = :present true end def destroy Puppet.info("Deleting network #{name}") begin client.release_network(datacenter, id) rescue Faraday::TimeoutError # Relase network is sync operation. Just ignore read timeout end @property_hash[:ensure] = :absent end end
require 'rails_helper' describe TicTacToe do it "can lookup games from the database" do created = TicTacToe.start_game 1,2 loaded = TicTacToe.lookup_game created.id expect(created.id).to eq loaded.id expect(loaded.player_turn? 1).to eq true end it "can record a move" do g = TicTacToe.start_game 4,7 g.record_move 3 expect(g.value_at 3).to eq :x end it "knows whos turn it is" do g = TicTacToe.start_game 4,7 g.record_move 3 g.record_move 5 g.record_move 1 expect(g.player_turn? 7).to eq true end end
class Words def initialize @words = YAML.load(File.read('words.yml')) @deck = {} @words.each do |category, words| @deck[category] = words.shuffle.map(&:capitalize) end end def get_word_at_level(level) return @deck[level.downcase].shift if @deck[level.downcase].any? return "No #{level} cards left" end def generate_category_list raw_cat = YAML.load(File.read('words.yml')) return raw_cat.keys.map(&:capitalize) end end
class AddAttachmentAvatarToMilks < ActiveRecord::Migration def self.up change_table :milks do |t| t.attachment :avatar end end def self.down remove_attachment :milks, :avatar end end
require 'spec_helper' describe "Static pages" do subject {page} describe "Home page" do before {visit root_path} it {should have_content('Welcome to Club-Biz!')} it {should have_title('Club-Biz')} it {should have_link('Sign in',href: signin_path)} it {should have_link('Sign up',href: signup_path)} it {should have_link('Want to sign up as a club? Register your club with Club-Biz', href: new_verification_path)} describe "for signed-in students" do let(:student) {FactoryGirl.create(:student)} before {sign_in student} it {should have_link('Browse Events',href: events_path)} it {should have_link('Browse Clubs',href: clubs_path)} it {should have_link('My Events',href: events_student_path(student))} it {should have_link('My Clubs',href: clubs_student_path(student))} it {should have_link('Messages',href: messages_student_path(student))} it {should have_link('Sign out',href: signout_path)} it {should_not have_link('Create event',href: new_event_path)} it {should_not have_link('Events',href:events_admin_path(student))} it {should_not have_link('Club profile',href:edit_club_path(student))} end describe "for signed-in admins" do let(:admin){FactoryGirl.create(:admin)} let(:club){FactoryGirl.create(:club)} let(:admin_detail){FactoryGirl.create(:admin_detail)} before {sign_in admin} it {should have_link('Create Event', href: new_event_path)} it {should have_link('Events', href:events_admin_path(admin))} it {should have_link('Club Profile', href:edit_club_path(club))} it {should have_link('Sign out',href: signout_path)} it {should_not have_link('Browse Events',href: events_path)} it {should_not have_link('Browse Clubs',href: clubs_path)} it {should_not have_link('My Events',href: events_student_path(admin))} it {should_not have_link('My Clubs',href: clubs_student_path(admin))} it {should_not have_link('Messages',href: messages_student_path(admin))} end end end
recipes = { hashbrowns: { description: 'Cripsy fried potatoes!', ingredients: ["Potatoes", "Butter", "Eggs", "Salt", "Pepper"], steps: ["1. Shred potatoes", "2. Add butter and eggs", "3. Fry"] }, pancakes: { description: 'Warm, fluffy buttermilk pancakes!', ingredients: ["Flour", 'Salt', 'Egg', 'Milk', 'Butter'], steps: ["1. Mix ingredients until smooth", "2. Pour mix on pan", "3. Flip when ready"] }, ice_cream: { description: 'Homemade vanilla ice cream!', ingredients: ['Milk', "Vanilla", 'Salt', "Cream"], steps: ["1. Stir milk, vanilla, and salt", "2. Beat cream and add milk mix", "3. Pour and let freeze, stirring occasionally"] } } # 1. The hash in ingredients.rb has signature Hash<Symbol, Array<String>> # 2. Hash<Hash, Array<Integer>> # 3. Array< Hash< Array<String>, Symbol> > # 4. The hash in the yellow box doesn't have a signature because the symbols # map to different data types
PatsMdb::Application.routes.draw do # generated routes resources :pets resources :owners resources :visits # semi-static page routes match 'home' => 'home#index', :as => :home match 'about' => 'home#about', :as => :about match 'contact' => 'home#contact', :as => :contact match 'privacy' => 'home#privacy', :as => :privacy # set the root url root :to => 'home#index' end
require 'swagger_helper' describe 'Auth SignUp' do path "/api/v1/users/signup" do post 'Sign Up a User' do tags 'Sign Up' consumes 'application/x-www-form-urlencoded' produces 'application/json' parameter name: :user, in: :body, schema: { type: :object, properties: { email: {type: :string}, password: {type: :string} }, required: ['email', 'password'] } response '200', 'user created' do schema type: :object, properties: { email: {type: :string}, access_token: {type: :string} } let(:user) { { email: 'srj@gmail.com', password: "password" } } run_test! end end end path "/api/v1/users/login" do post 'LogIn a User' do tags 'Log In' consumes 'application/x-www-form-urlencoded' produces 'application/json' parameter name: :user, in: :body, schema: { type: :object, properties: { email: {type: :string}, password: {type: :string} }, required: ['email', 'password'] } response '200', 'user login' do schema type: :object, properties: { email: {type: :string}, access_token: {type: :string} } let(:user) { { email: 'srj@gmail.com', password: "password" } } run_test! end end end path "/api/v1/users/{id}/cart" do get 'Get cart of specific user' do tags 'Get cart of specific user' consumes 'application/x-www-form-urlencoded' produces 'application/json' parameter name: :id, in: :path, schema: { type: :integer, } response '200', 'user cart' do examples 'application/json' => { id: 1, title: "hello" } run_test! end security [ bearer_auth: [] ] end end end describe 'Categories' do path "/api/v1/categories" do get 'List down all categories' do tags 'Categories' produces 'application/json' response '200', 'categories listed' do schema type: :array, items: {type: :object, properties: { id: {type: :string}, name: {type: :string}, category_id: {type: :integer}, description: {type: :string}, price: {type: :string}, model: {type: :int} } } run_test! end security [ bearer_auth: [] ] end end path "/api/v1/categories/{categoryId}/products" do get 'List down all products in a category' do tags 'List down all products in a category' produces 'application/json' parameter name: :categoryId, in: :path, schema: { type: :integer, } response '200', 'categories listed' do schema type: :array, items: {type: :object, properties: { id: {type: :string}, name: {type: :string}, category_id: {type: :integer}, description: {type: :string}, price: {type: :string}, model: {type: :int} } } run_test! end security [ bearer_auth: [] ] end end end describe 'Products' do path "/api/v1/products" do get 'List down all products' do tags 'products' produces 'application/json' response '200', 'Products listed' do schema type: :array, items: {type: :object, properties: { id: {type: :integer}, name: {type: :string}, category_id: {type: :integer}, description: {type: :string}, price: {type: :string}, make: {type: :int} } } run_test! end security [ bearer_auth: [] ] end end end describe 'User Cart' do after do |example| example.metadata[:response][:examples] = { 'application/json' => JSON.parse(response.body, symbolize_names: true) } end path "/api/v1/carts/add_product" do post 'Add Product to userCart' do tags 'Add Product to user cart' consumes 'application/json' produces 'application/json' parameter name: :user_cart, in: :body, schema: { type: :object, properties: { product_id: {type: :integer}, quantity: {type: :integer} }, required: ['product_id', 'quantity'] } response 200, 'Product Added' do examples 'application/json' => { id: 1, title: "hello" } after do |example| example.metadata[:response][:examples] = { 'application/json' => JSON.parse(response.body, symbolize_names: true) } end run_test! end security [ bearer_auth: [] ] end end end # cart_items: [ # { # id: 2, # cart_id: 6, # user_id: 11, # product_id: 1, # quantity: 1 # } # ]
require 'rails_helper' RSpec.describe "Update Agent", type: :request do include Warden::Test::Helpers include ApiHelpers before(:all) do @redis = Redis.new end it "won't allow unauthenticated user to update an agent" do org = FactoryGirl.create :org agent = FactoryGirl.create :agent, org: org put "/api/v1/orgs/#{org.id}/agents/#{agent.id}", nil, json_headers # test for the 401 status-code expect(response).to have_http_status 401 end it "won't allow badly authenticated user to update an agent" do org = FactoryGirl.create :org agent = FactoryGirl.create :agent, org: org user = create_user # Sign In sign_in_info = sign_in(user) auth_token = 'wrong_token' headers = json_headers headers = add_authentication_to_headers(headers, user.email, auth_token) url = "/api/v1/orgs/#{org.id}/agents/#{agent.id}" put url, nil, headers expect(response).to have_http_status 401 end it "will allow authenticated user from same org to update an agent" do org = FactoryGirl.create :org agent = FactoryGirl.create :agent, org: org, slug: 'foo' user = create_user org: org expect(org.users.count).to eq 2 old_encrypted_password = user.encrypted_password # Sign In sign_in_info = sign_in(user) auth_token = sign_in_info['auth_token'] headers = json_headers headers = add_authentication_to_headers(headers, user.email, auth_token) url = "/api/v1/orgs/#{org.id}/agents/#{agent.id}" params = {agent: {slug: 'bar'}} put url, params.to_json, headers expect(response).to have_http_status 201 new_agent_params = JSON.parse(response.body) new_password = new_agent_params['password'] expect(new_password).to be_present # Check right number of agents and users created expect(org.agents.count).to eq 1 expect(org.agents.first.name).to eq 'Bar' expect(org.agents.first.slug).to eq 'bar' expect(org.users.count).to eq 2 # Check correct values returned to agent expect(new_agent_params['slug']).to eq 'bar' expect(agent.user.encrypted_password).not_to eq old_encrypted_password # Check values passed to redis #redis_entry = @redis.get "agent_token:#{agent.token}" end it "will not allow authenticated user from different org to update an agent" do org = FactoryGirl.create :org agent = FactoryGirl.create :agent, org: org, slug: 'baz' user = create_user # Sign In sign_in_info = sign_in(user) auth_token = sign_in_info['auth_token'] headers = json_headers headers = add_authentication_to_headers(headers, user.email, auth_token) url = "/api/v1/orgs/#{org.id}/agents/#{agent.id}" params = {agent: {name: 'foo', slug: 'foo'}} put url, params.to_json, headers expect(response).to have_http_status 401 end end
=begin Swap Letters Sample Text and Starter File This is not an actual exercise. It is the sample text and class for the next two exercises. Sample Text Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed vulputate ipsum. Suspendisse commodo sem arcu. Donec a nisi elit. Nullam eget nisi commodo, volutpat quam a, viverra mauris. Nunc viverra sed massa a condimentum. Suspendisse ornare justo nulla, sit amet mollis eros sollicitudin et. Etiam maximus molestie eros, sit amet dictum dolor ornare bibendum. Morbi ut massa nec lorem tincidunt elementum vitae id magna. Cras et varius mauris, at pharetra mi. Class and method to Test class Text def initialize(text) @text = text end def swap(letter_one, letter_two) @text.gsub(letter_one, letter_two) end end =end
# oracle_enhanced_adapter.rb -- ActiveRecord adapter for Oracle 8i, 9i, 10g, 11g # # Authors or original oracle_adapter: Graham Jenkins, Michael Schoen # # Current maintainer: Raimonds Simanovskis (http://blog.rayapps.com) # ######################################################################### # # See History.txt for changes added to original oracle_adapter.rb # ######################################################################### # # From original oracle_adapter.rb: # # Implementation notes: # 1. Redefines (safely) a method in ActiveRecord to make it possible to # implement an autonumbering solution for Oracle. # 2. The OCI8 driver is patched to properly handle values for LONG and # TIMESTAMP columns. The driver-author has indicated that a future # release of the driver will obviate this patch. # 3. LOB support is implemented through an after_save callback. # 4. Oracle does not offer native LIMIT and OFFSET options; this # functionality is mimiced through the use of nested selects. # See http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:127412348064 # # Do what you want with this code, at your own peril, but if any # significant portion of my code remains then please acknowledge my # contribution. # portions Copyright 2005 Graham Jenkins require 'active_record/connection_adapters/abstract_adapter' require 'active_record/connection_adapters/oracle_enhanced_connection' module ActiveRecord class Base def self.oracle_enhanced_connection(config) if config[:emulate_oracle_adapter] == true # allows the enhanced adapter to look like the OracleAdapter. Useful to pick up # conditionals in the rails activerecord test suite require 'active_record/connection_adapters/emulation/oracle_adapter' ConnectionAdapters::OracleAdapter.new( ConnectionAdapters::OracleEnhancedConnection.create(config), logger) else ConnectionAdapters::OracleEnhancedAdapter.new( ConnectionAdapters::OracleEnhancedConnection.create(config), logger) end end # RSI: specify table columns which should be ifnored def self.ignore_table_columns(*args) connection.ignore_table_columns(table_name,*args) end # RSI: specify which table columns should be treated as date (without time) def self.set_date_columns(*args) connection.set_type_for_columns(table_name,:date,*args) end # RSI: specify which table columns should be treated as datetime def self.set_datetime_columns(*args) connection.set_type_for_columns(table_name,:datetime,*args) end # RSI: specify which table columns should be treated as booleans def self.set_boolean_columns(*args) connection.set_type_for_columns(table_name,:boolean,*args) end # After setting large objects to empty, select the OCI8::LOB # and write back the data. after_save :enhanced_write_lobs def enhanced_write_lobs #:nodoc: if connection.is_a?(ConnectionAdapters::OracleEnhancedAdapter) && !(self.class.custom_create_method || self.class.custom_update_method) connection.write_lobs(self.class.table_name, self.class, attributes) end end private :enhanced_write_lobs class << self # RSI: patch ORDER BY to work with LOBs def add_order_with_lobs!(sql, order, scope = :auto) if connection.is_a?(ConnectionAdapters::OracleEnhancedAdapter) order = connection.lob_order_by_expression(self, order) if order orig_scope = scope scope = scope(:find) if :auto == scope if scope new_scope_order = connection.lob_order_by_expression(self, scope[:order]) if new_scope_order != scope[:order] scope = scope.merge(:order => new_scope_order) else scope = orig_scope end end end add_order_without_lobs!(sql, order, scope = :auto) end private :add_order_with_lobs! alias_method :add_order_without_lobs!, :add_order! alias_method :add_order!, :add_order_with_lobs! end # RSI: get table comment from schema definition def self.table_comment connection.table_comment(self.table_name) end end module ConnectionAdapters #:nodoc: class OracleEnhancedColumn < Column #:nodoc: attr_reader :table_name, :forced_column_type def initialize(name, default, sql_type = nil, null = true, table_name = nil, forced_column_type = nil) @table_name = table_name @forced_column_type = forced_column_type super(name, default, sql_type, null) end def type_cast(value) return guess_date_or_time(value) if type == :datetime && OracleEnhancedAdapter.emulate_dates super end # convert something to a boolean # RSI: added y as boolean value def self.value_to_boolean(value) if value == true || value == false value elsif value.is_a?(String) && value.blank? nil else %w(true t 1 y +).include?(value.to_s.downcase) end end # RSI: convert Time or DateTime value to Date for :date columns def self.string_to_date(string) return string.to_date if string.is_a?(Time) || string.is_a?(DateTime) super end # RSI: convert Date value to Time for :datetime columns def self.string_to_time(string) return string.to_time if string.is_a?(Date) && !OracleEnhancedAdapter.emulate_dates super end # RSI: get column comment from schema definition # will work only if using default ActiveRecord connection def comment ActiveRecord::Base.connection.column_comment(@table_name, name) end private def simplified_type(field_type) return :boolean if OracleEnhancedAdapter.emulate_booleans && field_type == 'NUMBER(1)' return :boolean if OracleEnhancedAdapter.emulate_booleans_from_strings && (forced_column_type == :boolean || OracleEnhancedAdapter.is_boolean_column?(name, field_type, table_name)) case field_type when /date/i forced_column_type || (:date if OracleEnhancedAdapter.emulate_dates_by_column_name && OracleEnhancedAdapter.is_date_column?(name, table_name)) || :datetime when /timestamp/i then :timestamp when /time/i then :datetime when /decimal|numeric|number/i return :integer if extract_scale(field_type) == 0 # RSI: if column name is ID or ends with _ID return :integer if OracleEnhancedAdapter.emulate_integers_by_column_name && OracleEnhancedAdapter.is_integer_column?(name, table_name) :decimal else super end end def guess_date_or_time(value) value.respond_to?(:hour) && (value.hour == 0 and value.min == 0 and value.sec == 0) ? Date.new(value.year, value.month, value.day) : value end class <<self protected def fallback_string_to_date(string) if OracleEnhancedAdapter.string_to_date_format || OracleEnhancedAdapter.string_to_time_format return (string_to_date_or_time_using_format(string).to_date rescue super) end super end def fallback_string_to_time(string) if OracleEnhancedAdapter.string_to_time_format || OracleEnhancedAdapter.string_to_date_format return (string_to_date_or_time_using_format(string).to_time rescue super) end super end def string_to_date_or_time_using_format(string) if OracleEnhancedAdapter.string_to_time_format && dt=Date._strptime(string, OracleEnhancedAdapter.string_to_time_format) return Time.mktime(*dt.values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday)) end DateTime.strptime(string, OracleEnhancedAdapter.string_to_date_format) end end end # This is an Oracle/OCI adapter for the ActiveRecord persistence # framework. It relies upon the OCI8 driver, which works with Oracle 8i # and above. Most recent development has been on Debian Linux against # a 10g database, ActiveRecord 1.12.1 and OCI8 0.1.13. # See: http://rubyforge.org/projects/ruby-oci8/ # # Usage notes: # * Key generation assumes a "${table_name}_seq" sequence is available # for all tables; the sequence name can be changed using # ActiveRecord::Base.set_sequence_name. When using Migrations, these # sequences are created automatically. # * Oracle uses DATE or TIMESTAMP datatypes for both dates and times. # Consequently some hacks are employed to map data back to Date or Time # in Ruby. If the column_name ends in _time it's created as a Ruby Time. # Else if the hours/minutes/seconds are 0, I make it a Ruby Date. Else # it's a Ruby Time. This is a bit nasty - but if you use Duck Typing # you'll probably not care very much. In 9i and up it's tempting to # map DATE to Date and TIMESTAMP to Time, but too many databases use # DATE for both. Timezones and sub-second precision on timestamps are # not supported. # * Default values that are functions (such as "SYSDATE") are not # supported. This is a restriction of the way ActiveRecord supports # default values. # * Support for Oracle8 is limited by Rails' use of ANSI join syntax, which # is supported in Oracle9i and later. You will need to use #finder_sql for # has_and_belongs_to_many associations to run against Oracle8. # # Required parameters: # # * <tt>:username</tt> # * <tt>:password</tt> # * <tt>:database</tt> class OracleEnhancedAdapter < AbstractAdapter @@emulate_booleans = true cattr_accessor :emulate_booleans @@emulate_dates = false cattr_accessor :emulate_dates # RSI: set to true if columns with DATE in their name should be emulated as date @@emulate_dates_by_column_name = false cattr_accessor :emulate_dates_by_column_name def self.is_date_column?(name, table_name = nil) name =~ /(^|_)date(_|$)/i end # RSI: instance method uses at first check if column type defined at class level def is_date_column?(name, table_name = nil) case get_type_for_column(table_name, name) when nil self.class.is_date_column?(name, table_name) when :date true else false end end # RSI: set to true if NUMBER columns with ID at the end of their name should be emulated as integers @@emulate_integers_by_column_name = false cattr_accessor :emulate_integers_by_column_name def self.is_integer_column?(name, table_name = nil) name =~ /(^|_)id$/i end # RSI: set to true if CHAR(1), VARCHAR2(1) columns or VARCHAR2 columns with FLAG or YN at the end of their name # should be emulated as booleans @@emulate_booleans_from_strings = false cattr_accessor :emulate_booleans_from_strings def self.is_boolean_column?(name, field_type, table_name = nil) return true if ["CHAR(1)","VARCHAR2(1)"].include?(field_type) field_type =~ /^VARCHAR2/ && (name =~ /_flag$/i || name =~ /_yn$/i) end def self.boolean_to_string(bool) bool ? "Y" : "N" end # RSI: use to set NLS specific date formats which will be used when assigning string to :date and :datetime columns @@string_to_date_format = @@string_to_time_format = nil cattr_accessor :string_to_date_format, :string_to_time_format def adapter_name #:nodoc: 'OracleEnhanced' end def supports_migrations? #:nodoc: true end def native_database_types #:nodoc: { :primary_key => "NUMBER(38) NOT NULL PRIMARY KEY", :string => { :name => "VARCHAR2", :limit => 255 }, :text => { :name => "CLOB" }, :integer => { :name => "NUMBER", :limit => 38 }, :float => { :name => "NUMBER" }, :decimal => { :name => "DECIMAL" }, :datetime => { :name => "DATE" }, # RSI: changed to native TIMESTAMP type # :timestamp => { :name => "DATE" }, :timestamp => { :name => "TIMESTAMP" }, :time => { :name => "DATE" }, :date => { :name => "DATE" }, :binary => { :name => "BLOB" }, # RSI: if emulate_booleans_from_strings then store booleans in VARCHAR2 :boolean => emulate_booleans_from_strings ? { :name => "VARCHAR2", :limit => 1 } : { :name => "NUMBER", :limit => 1 } } end def table_alias_length 30 end # Returns an array of arrays containing the field values. # Order is the same as that returned by #columns. def select_rows(sql, name = nil) # last parameter indicates to return also column list result, columns = select(sql, name, true) result.map{ |v| columns.map{|c| v[c]} } end # QUOTING ================================================== # # see: abstract/quoting.rb # camelCase column names need to be quoted; not that anyone using Oracle # would really do this, but handling this case means we pass the test... def quote_column_name(name) #:nodoc: name.to_s =~ /[A-Z]/ ? "\"#{name}\"" : quote_oracle_reserved_words(name) end # unescaped table name should start with letter and # contain letters, digits, _, $ or # # can be prefixed with schema name # CamelCase table names should be quoted def self.valid_table_name?(name) name = name.to_s name =~ /^([A-Za-z_0-9]+\.)?[a-z][a-z_0-9\$#]*$/ || name =~ /^([A-Za-z_0-9]+\.)?[A-Z][A-Z_0-9\$#]*$/ ? true : false end # abstract_adapter calls quote_column_name from quote_table_name, so prevent that def quote_table_name(name) if self.class.valid_table_name?(name) name else "\"#{name}\"" end end def quote_string(s) #:nodoc: s.gsub(/'/, "''") end def quote(value, column = nil) #:nodoc: if value && column case column.type when :text, :binary %Q{empty_#{ column.sql_type.downcase rescue 'blob' }()} # RSI: TIMESTAMP support when :timestamp quote_timestamp_with_to_timestamp(value) # RSI: NLS_DATE_FORMAT independent DATE support when :date, :time, :datetime quote_date_with_to_date(value) else super end elsif value.acts_like?(:date) quote_date_with_to_date(value) elsif value.acts_like?(:time) value.to_i == value.to_f ? quote_date_with_to_date(value) : quote_timestamp_with_to_timestamp(value) else super end end def quoted_true return "'#{self.class.boolean_to_string(true)}'" if emulate_booleans_from_strings "1" end def quoted_false return "'#{self.class.boolean_to_string(false)}'" if emulate_booleans_from_strings "0" end # RSI: should support that composite_primary_keys gem will pass date as string def quote_date_with_to_date(value) value = value.to_s(:db) if value.acts_like?(:date) || value.acts_like?(:time) "TO_DATE('#{value}','YYYY-MM-DD HH24:MI:SS')" end def quote_timestamp_with_to_timestamp(value) # add up to 9 digits of fractional seconds to inserted time value = "#{value.to_s(:db)}.#{("%.6f"%value.to_f).split('.')[1]}" if value.acts_like?(:time) "TO_TIMESTAMP('#{value}','YYYY-MM-DD HH24:MI:SS.FF6')" end # CONNECTION MANAGEMENT ==================================== # # If SQL statement fails due to lost connection then reconnect # and retry SQL statement if autocommit mode is enabled. # By default this functionality is disabled. @auto_retry = false attr_reader :auto_retry def auto_retry=(value) @auto_retry = value @connection.auto_retry = value if @connection end def raw_connection @connection.raw_connection end # Returns true if the connection is active. def active? # Pings the connection to check if it's still good. Note that an # #active? method is also available, but that simply returns the # last known state, which isn't good enough if the connection has # gone stale since the last use. @connection.ping rescue OracleEnhancedConnectionException false end # Reconnects to the database. def reconnect! @connection.reset! rescue OracleEnhancedConnectionException => e @logger.warn "#{adapter_name} automatic reconnection failed: #{e.message}" end # Disconnects from the database. def disconnect! @connection.logoff rescue nil end # DATABASE STATEMENTS ====================================== # # see: abstract/database_statements.rb def execute(sql, name = nil) #:nodoc: log(sql, name) { @connection.exec sql } end # Returns the next sequence value from a sequence generator. Not generally # called directly; used by ActiveRecord to get the next primary key value # when inserting a new database record (see #prefetch_primary_key?). def next_sequence_value(sequence_name) select_one("select #{sequence_name}.nextval id from dual")['id'] end def begin_db_transaction #:nodoc: @connection.autocommit = false end def commit_db_transaction #:nodoc: @connection.commit ensure @connection.autocommit = true end def rollback_db_transaction #:nodoc: @connection.rollback ensure @connection.autocommit = true end def add_limit_offset!(sql, options) #:nodoc: # RSI: added to_i for limit and offset to protect from SQL injection offset = (options[:offset] || 0).to_i if limit = options[:limit] limit = limit.to_i sql.replace "select * from (select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_ where rownum <= #{offset+limit}) where raw_rnum_ > #{offset}" elsif offset > 0 sql.replace "select * from (select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_) where raw_rnum_ > #{offset}" end end # Returns true for Oracle adapter (since Oracle requires primary key # values to be pre-fetched before insert). See also #next_sequence_value. def prefetch_primary_key?(table_name = nil) true end def default_sequence_name(table, column) #:nodoc: quote_table_name("#{table}_seq") end # Inserts the given fixture into the table. Overridden to properly handle lobs. def insert_fixture(fixture, table_name) super klass = fixture.class_name.constantize rescue nil if klass.respond_to?(:ancestors) && klass.ancestors.include?(ActiveRecord::Base) write_lobs(table_name, klass, fixture) end end # Writes LOB values from attributes, as indicated by the LOB columns of klass. def write_lobs(table_name, klass, attributes) # is class with composite primary key> is_with_cpk = klass.respond_to?(:composite?) && klass.composite? if is_with_cpk id = klass.primary_key.map {|pk| attributes[pk.to_s] } else id = quote(attributes[klass.primary_key]) end klass.columns.select { |col| col.sql_type =~ /LOB$/i }.each do |col| value = attributes[col.name] # RSI: changed sequence of next two lines - should check if value is nil before converting to yaml next if value.nil? || (value == '') value = value.to_yaml if col.text? && klass.serialized_attributes[col.name] uncached do if is_with_cpk lob = select_one("SELECT #{col.name} FROM #{table_name} WHERE #{klass.composite_where_clause(id)} FOR UPDATE", 'Writable Large Object')[col.name] else lob = select_one("SELECT #{col.name} FROM #{table_name} WHERE #{klass.primary_key} = #{id} FOR UPDATE", 'Writable Large Object')[col.name] end @connection.write_lob(lob, value, col.type == :binary) end end end # RSI: change LOB column for ORDER BY clause # just first 100 characters are taken for ordering def lob_order_by_expression(klass, order) return order if order.nil? changed = false new_order = order.to_s.strip.split(/, */).map do |order_by_col| column_name, asc_desc = order_by_col.split(/ +/) if column = klass.columns.detect { |col| col.name == column_name && col.sql_type =~ /LOB$/i} changed = true "DBMS_LOB.SUBSTR(#{column_name},100,1) #{asc_desc}" else order_by_col end end.join(', ') changed ? new_order : order end # SCHEMA STATEMENTS ======================================== # # see: abstract/schema_statements.rb def current_database #:nodoc: select_one("select sys_context('userenv','db_name') db from dual")["db"] end # RSI: changed select from user_tables to all_tables - much faster in large data dictionaries def tables(name = nil) #:nodoc: select_all("select decode(table_name,upper(table_name),lower(table_name),table_name) name from all_tables where owner = sys_context('userenv','session_user')").map {|t| t['name']} end cattr_accessor :all_schema_indexes # This method selects all indexes at once, and caches them in a class variable. # Subsequent index calls get them from the variable, without going to the DB. def indexes(table_name, name = nil) (owner, table_name) = @connection.describe(table_name) unless all_schema_indexes result = select_all(<<-SQL) SELECT lower(i.table_name) as table_name, lower(i.index_name) as index_name, i.uniqueness, lower(c.column_name) as column_name FROM all_indexes i, all_ind_columns c WHERE i.owner = '#{owner}' AND i.table_owner = '#{owner}' AND c.index_name = i.index_name AND c.index_owner = i.owner AND NOT EXISTS (SELECT uc.index_name FROM all_constraints uc WHERE uc.index_name = i.index_name AND uc.owner = i.owner AND uc.constraint_type = 'P') ORDER BY i.index_name, c.column_position SQL current_index = nil self.all_schema_indexes = [] result.each do |row| # have to keep track of indexes because above query returns dups # there is probably a better query we could figure out if current_index != row['index_name'] self.all_schema_indexes << ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(row['table_name'], row['index_name'], row['uniqueness'] == "UNIQUE", []) current_index = row['index_name'] end self.all_schema_indexes.last.columns << row['column_name'] end end # Return the indexes just for the requested table, since AR is structured that way table_name = table_name.downcase all_schema_indexes.select{|i| i.table == table_name} end # RSI: set ignored columns for table def ignore_table_columns(table_name, *args) @ignore_table_columns ||= {} @ignore_table_columns[table_name] ||= [] @ignore_table_columns[table_name] += args.map{|a| a.to_s.downcase} @ignore_table_columns[table_name].uniq! end def ignored_table_columns(table_name) @ignore_table_columns ||= {} @ignore_table_columns[table_name] end # RSI: set explicit type for specified table columns def set_type_for_columns(table_name, column_type, *args) @table_column_type ||= {} @table_column_type[table_name] ||= {} args.each do |col| @table_column_type[table_name][col.to_s.downcase] = column_type end end def get_type_for_column(table_name, column_name) @table_column_type && @table_column_type[table_name] && @table_column_type[table_name][column_name.to_s.downcase] end def clear_types_for_columns @table_column_type = nil end def columns(table_name, name = nil) #:nodoc: # RSI: get ignored_columns by original table name ignored_columns = ignored_table_columns(table_name) (owner, desc_table_name) = @connection.describe(table_name) table_cols = <<-SQL select column_name as name, data_type as sql_type, data_default, nullable, decode(data_type, 'NUMBER', data_precision, 'FLOAT', data_precision, 'VARCHAR2', data_length, 'CHAR', data_length, null) as limit, decode(data_type, 'NUMBER', data_scale, null) as scale from all_tab_columns where owner = '#{owner}' and table_name = '#{desc_table_name}' order by column_id SQL # RSI: added deletion of ignored columns select_all(table_cols, name).delete_if do |row| ignored_columns && ignored_columns.include?(row['name'].downcase) end.map do |row| limit, scale = row['limit'], row['scale'] if limit || scale row['sql_type'] << "(#{(limit || 38).to_i}" + ((scale = scale.to_i) > 0 ? ",#{scale})" : ")") end # clean up odd default spacing from Oracle if row['data_default'] row['data_default'].sub!(/^(.*?)\s*$/, '\1') row['data_default'].sub!(/^'(.*)'$/, '\1') row['data_default'] = nil if row['data_default'] =~ /^(null|empty_[bc]lob\(\))$/i end OracleEnhancedColumn.new(oracle_downcase(row['name']), row['data_default'], row['sql_type'], row['nullable'] == 'Y', # RSI: pass table name for table specific column definitions table_name, # RSI: pass column type if specified in class definition get_type_for_column(table_name, oracle_downcase(row['name']))) end end # RSI: default sequence start with value @@default_sequence_start_value = 10000 cattr_accessor :default_sequence_start_value def create_table(name, options = {}, &block) #:nodoc: create_sequence = options[:id] != false column_comments = {} super(name, options) do |t| # store that primary key was defined in create_table block unless create_sequence class <<t attr_accessor :create_sequence def primary_key(*args) self.create_sequence = true super(*args) end end end # store column comments class <<t attr_accessor :column_comments def column(name, type, options = {}) if options[:comment] self.column_comments ||= {} self.column_comments[name] = options[:comment] end super(name, type, options) end end result = block.call(t) create_sequence = create_sequence || t.create_sequence column_comments = t.column_comments if t.column_comments end seq_name = options[:sequence_name] || quote_table_name("#{name}_seq") seq_start_value = options[:sequence_start_value] || default_sequence_start_value execute "CREATE SEQUENCE #{seq_name} START WITH #{seq_start_value}" if create_sequence add_table_comment name, options[:comment] column_comments.each do |column_name, comment| add_comment name, column_name, comment end end def rename_table(name, new_name) #:nodoc: execute "RENAME #{quote_table_name(name)} TO #{quote_table_name(new_name)}" execute "RENAME #{quote_table_name("#{name}_seq")} TO #{quote_table_name("#{new_name}_seq")}" rescue nil end def drop_table(name, options = {}) #:nodoc: super(name) seq_name = options[:sequence_name] || quote_table_name("#{name}_seq") execute "DROP SEQUENCE #{seq_name}" rescue nil end # clear cached indexes when adding new index def add_index(table_name, column_name, options = {}) self.all_schema_indexes = nil super end # clear cached indexes when removing index def remove_index(table_name, options = {}) #:nodoc: self.all_schema_indexes = nil execute "DROP INDEX #{index_name(table_name, options)}" end def add_column(table_name, column_name, type, options = {}) add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" options[:type] = type add_column_options!(add_column_sql, options) execute(add_column_sql) end def change_column_default(table_name, column_name, default) #:nodoc: execute "ALTER TABLE #{quote_table_name(table_name)} MODIFY #{quote_column_name(column_name)} DEFAULT #{quote(default)}" end def change_column_null(table_name, column_name, null, default = nil) column = column_for(table_name, column_name) unless null || default.nil? execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") end change_column table_name, column_name, column.sql_type, :null => null end def change_column(table_name, column_name, type, options = {}) #:nodoc: column = column_for(table_name, column_name) # remove :null option if its value is the same as current column definition # otherwise Oracle will raise error if options.has_key?(:null) && options[:null] == column.null options[:null] = nil end change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} MODIFY #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" options[:type] = type add_column_options!(change_column_sql, options) execute(change_column_sql) end def rename_column(table_name, column_name, new_column_name) #:nodoc: execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} to #{quote_column_name(new_column_name)}" end def remove_column(table_name, column_name) #:nodoc: execute "ALTER TABLE #{quote_table_name(table_name)} DROP COLUMN #{quote_column_name(column_name)}" end # RSI: table and column comments def add_comment(table_name, column_name, comment) return if comment.blank? execute "COMMENT ON COLUMN #{quote_table_name(table_name)}.#{column_name} IS '#{comment}'" end def add_table_comment(table_name, comment) return if comment.blank? execute "COMMENT ON TABLE #{quote_table_name(table_name)} IS '#{comment}'" end def table_comment(table_name) (owner, table_name) = @connection.describe(table_name) select_value <<-SQL SELECT comments FROM all_tab_comments WHERE owner = '#{owner}' AND table_name = '#{table_name}' SQL end def column_comment(table_name, column_name) (owner, table_name) = @connection.describe(table_name) select_value <<-SQL SELECT comments FROM all_col_comments WHERE owner = '#{owner}' AND table_name = '#{table_name}' AND column_name = '#{column_name.upcase}' SQL end # Find a table's primary key and sequence. # *Note*: Only primary key is implemented - sequence will be nil. def pk_and_sequence_for(table_name) (owner, table_name) = @connection.describe(table_name) # RSI: changed select from all_constraints to user_constraints - much faster in large data dictionaries pks = select_values(<<-SQL, 'Primary Key') select cc.column_name from user_constraints c, user_cons_columns cc where c.owner = '#{owner}' and c.table_name = '#{table_name}' and c.constraint_type = 'P' and cc.owner = c.owner and cc.constraint_name = c.constraint_name SQL # only support single column keys pks.size == 1 ? [oracle_downcase(pks.first), nil] : nil end def structure_dump #:nodoc: s = select_all("select sequence_name from user_sequences order by 1").inject("") do |structure, seq| structure << "create sequence #{seq.to_a.first.last};\n\n" end # RSI: changed select from user_tables to all_tables - much faster in large data dictionaries select_all("select table_name from all_tables where owner = sys_context('userenv','session_user') order by 1").inject(s) do |structure, table| ddl = "create table #{table.to_a.first.last} (\n " cols = select_all(%Q{ select column_name, data_type, data_length, char_used, char_length, data_precision, data_scale, data_default, nullable from user_tab_columns where table_name = '#{table.to_a.first.last}' order by column_id }).map do |row| col = "#{row['column_name'].downcase} #{row['data_type'].downcase}" if row['data_type'] =='NUMBER' and !row['data_precision'].nil? col << "(#{row['data_precision'].to_i}" col << ",#{row['data_scale'].to_i}" if !row['data_scale'].nil? col << ')' elsif row['data_type'].include?('CHAR') length = row['char_used'] == 'C' ? row['char_length'].to_i : row['data_length'].to_i col << "(#{length})" end col << " default #{row['data_default']}" if !row['data_default'].nil? col << ' not null' if row['nullable'] == 'N' col end ddl << cols.join(",\n ") ddl << ");\n\n" structure << ddl end end def structure_drop #:nodoc: s = select_all("select sequence_name from user_sequences order by 1").inject("") do |drop, seq| drop << "drop sequence #{seq.to_a.first.last};\n\n" end # RSI: changed select from user_tables to all_tables - much faster in large data dictionaries select_all("select table_name from all_tables where owner = sys_context('userenv','session_user') order by 1").inject(s) do |drop, table| drop << "drop table #{table.to_a.first.last} cascade constraints;\n\n" end end def add_column_options!(sql, options) #:nodoc: type = options[:type] || ((column = options[:column]) && column.type) type = type && type.to_sym # handle case of defaults for CLOB columns, which would otherwise get "quoted" incorrectly if options_include_default?(options) if type == :text sql << " DEFAULT #{quote(options[:default])}" else # from abstract adapter sql << " DEFAULT #{quote(options[:default], options[:column])}" end end # must explicitly add NULL or NOT NULL to allow change_column to work on migrations if options[:null] == false sql << " NOT NULL" elsif options[:null] == true sql << " NULL" unless type == :primary_key end end # SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause. # # Oracle requires the ORDER BY columns to be in the SELECT list for DISTINCT # queries. However, with those columns included in the SELECT DISTINCT list, you # won't actually get a distinct list of the column you want (presuming the column # has duplicates with multiple values for the ordered-by columns. So we use the # FIRST_VALUE function to get a single (first) value for each column, effectively # making every row the same. # # distinct("posts.id", "posts.created_at desc") def distinct(columns, order_by) return "DISTINCT #{columns}" if order_by.blank? # construct a valid DISTINCT clause, ie. one that includes the ORDER BY columns, using # FIRST_VALUE such that the inclusion of these columns doesn't invalidate the DISTINCT order_columns = order_by.split(',').map { |s| s.strip }.reject(&:blank?) order_columns = order_columns.zip((0...order_columns.size).to_a).map do |c, i| "FIRST_VALUE(#{c.split.first}) OVER (PARTITION BY #{columns} ORDER BY #{c}) AS alias_#{i}__" end sql = "DISTINCT #{columns}, " sql << order_columns * ", " end # ORDER BY clause for the passed order option. # # Uses column aliases as defined by #distinct. def add_order_by_for_association_limiting!(sql, options) return sql if options[:order].blank? order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?) order.map! {|s| $1 if s =~ / (.*)/} order = order.zip((0...order.size).to_a).map { |s,i| "alias_#{i}__ #{s}" }.join(', ') sql << " ORDER BY #{order}" end private def select(sql, name = nil, return_column_names = false) log(sql, name) do @connection.select(sql, name, return_column_names) end end def oracle_downcase(column_name) @connection.oracle_downcase(column_name) end def column_for(table_name, column_name) unless column = columns(table_name).find { |c| c.name == column_name.to_s } raise "No such column: #{table_name}.#{column_name}" end column end end end end # RSI: Added LOB writing callback for sessions stored in database # Otherwise it is not working as Session class is defined before OracleAdapter is loaded in Rails 2.0 if defined?(CGI::Session::ActiveRecordStore::Session) if !CGI::Session::ActiveRecordStore::Session.respond_to?(:after_save_callback_chain) || CGI::Session::ActiveRecordStore::Session.after_save_callback_chain.detect{|cb| cb.method == :enhanced_write_lobs}.nil? class CGI::Session::ActiveRecordStore::Session after_save :enhanced_write_lobs end end end # RSI: load custom create, update, delete methods functionality # rescue LoadError if ruby-plsql gem cannot be loaded begin require 'active_record/connection_adapters/oracle_enhanced_procedures' rescue LoadError if defined?(RAILS_DEFAULT_LOGGER) RAILS_DEFAULT_LOGGER.info "INFO: ActiveRecord oracle_enhanced adapter could not load ruby-plsql gem. "+ "Custom create, update and delete methods will not be available." end end # RSI: load additional methods for composite_primary_keys support require 'active_record/connection_adapters/oracle_enhanced_cpk' # RSI: load patch for dirty tracking methods require 'active_record/connection_adapters/oracle_enhanced_dirty' # RSI: load rake tasks definitions begin require 'active_record/connection_adapters/oracle_enhanced_tasks' rescue LoadError end if defined?(RAILS_ROOT) # handles quoting of oracle reserved words require 'active_record/connection_adapters/oracle_enhanced_reserved_words' # add BigDecimal#to_d, Fixnum#to_d and Bignum#to_d methods if not already present require 'active_record/connection_adapters/oracle_enhanced_core_ext'
require "application_system_test_case" class CountriesTest < ApplicationSystemTestCase setup do @country = countries(:one) end test "visiting the index" do visit countries_url assert_selector "h1", text: "Countries" end test "creating a Country" do visit countries_url click_on "New Country" click_on "Create Country" assert_text "Country was successfully created" click_on "Back" end test "updating a Country" do visit countries_url click_on "Edit", match: :first click_on "Update Country" assert_text "Country was successfully updated" click_on "Back" end test "destroying a Country" do visit countries_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Country was successfully destroyed" end end
class Api::V1::Transactions::TransactionsRandomController < ApplicationController def show @transaction = Transaction.random end end