Watir inspecting json in firefox "network" tab - Parsing - ruby

I'm not 100% sure if Im asking the right question.
There's a website I go to that uses has a JSON string that I need to access. I can see the location of the JSON string in Firefox's "network tab" by clicking F12 and selecting the "Network" tab.
So I thought i could access the file by going into the temporary internet files, but no dice.
I also thought watir could access the temporary internet files through itself, but all i could find is this.
require 'watir-webdriver'
$browser = Watir::Browser.new
$browser.methods
=> [:driver, :wd, :inspect, :goto, :back, :forward, :url, :title, :close, :quit, :cookies, :name, :text, :html, :alert, :refresh, :wait, :ready_state, :status, :execute_script, :send_keys, :screenshot, :add_checker, :disable_checker, :run_checkers, :exist?, :exists?, :assert_exists, :reset!, :browser, :wait_until, :wait_while, :windows, :window, :element, :elements, :extract_selector, :a, :as, :abbr, :abbrs, :address, :addresses, :area, :areas, :article, :articles, :aside, :asides, :audio, :audios, :b, :bs, :base, :bases, :bdi, :bdis, :bdo, :bdos, :blockquote, :blockquotes, :body, :bodys, :br, :brs, :button, :buttons, :canvas, :canvases, :caption, :captions, :cite, :cites, :code, :codes, :col, :cols, :colgroup, :colgroups, :data, :datas, :datalist, :datalists, :dd, :dds, :del, :dels, :details, :detailses, :dfn, :dfns, :dialog, :dialogs, :div, :divs, :dl, :dls, :dt, :dts, :em, :ems, :embed, :embeds, :fieldset, :fieldsets, :figcaption, :figcaptions, :figure, :figures, :footer, :footers, :form, :forms, :frameset, :framesets, :h1, :h1s, :h2, :h2s, :h3, :h3s, :h4, :h4s, :h5, :h5s, :h6, :h6s, :head, :heads, :header, :headers, :hgroup, :hgroups, :hr, :hrs, :htmls, :i, :is, :iframe, :iframes, :img, :imgs, :input, :inputs, :ins, :inses, :kbd, :kbds, :keygen, :keygens, :label, :labels, :legend, :legends, :li, :lis, :main, :mains, :map, :maps, :mark, :marks, :menu, :menus, :menuitem, :menuitems, :meta, :metas, :meter, :meters, :nav, :navs, :noscript, :noscripts, :object, :objects, :ol, :ols, :optgroup, :optgroups, :option, :options, :output, :outputs, :p, :ps, :param, :params, :pre, :pres, :progress, :progresses, :q, :qs, :rp, :rps, :rt, :rts, :ruby, :rubies, :s, :ss, :samp, :samps, :script, :scripts, :section, :sections, :select, :selects, :small, :smalls, :source, :sources, :span, :spans, :strong, :strongs, :style, :styles, :sub, :subs, :summary, :summaries, :sup, :sups, :table, :tables, :tbody, :tbodys, :td, :tds, :template, :templates, :textarea, :textareas, :tfoot, :tfoots, :th, :ths, :thead, :theads, :time, :times, :titles, :tr, :trs, :track, :tracks, :u, :us, :ul, :uls, :var, :vars, :video, :videos, :wbr, :wbrs, :checkbox, :checkboxes, :file_field, :file_fields, :font, :fonts, :frame, :frames, :hidden, :hiddens, :image, :images, :link, :links, :radio, :radios, :select_list, :select_lists, :text_field, :text_fields, :field_set, :field_sets, :psych_to_yaml, :to_yaml, :to_yaml_properties, :dclone, :to_json, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
There is a way to access everything else but the json temporary file i need to access.
I haven't seen any documentation on this, because I'm not sure I'm asking the correct questions.
Update:
The method is a 200 POST with the extension type json.

Related

while population sub category dropdown receive below error active admin

Error:-
ActionView::MissingTemplate (Missing template admin/blogs/get_child_category, active_admin/resource/get_child_category, active_admin/base/get_child_category, inherited_resources/base/get_child_category, application/get_child_category with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :vtt, :png, :jpeg, :gif, :bmp, :tiff, :svg, :mpeg, :mp3, :ogg, :m4a, :webm, :mp4, :otf, :ttf, :woff, :woff2, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip, :gzip], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :arb, :jbuilder]}. Searched in:
* "/home/rakesh/Documents/codetoart-website/app/views"
admin/category.rb
form do |f|
f.inputs do
.....
f.input :Category,:input_html => {
:onchange => remote_request(:post, :get_child_category, {:child_category_id=>"$('#blog_category_id').val()"}, :child_category_id)
}
f.input :child_category_id
.....
end
f.actions
end
method:-
controller do
def get_child_category
#child_category = Category.where(:parent_id => params[:child_category_id])
render :text=>view_context.options_from_collection_for_select(#child_category, :id, :name)
end
end
application_helper.rb
def remote_request(type, path, params={}, target_tag_id)
"$.#{type}('#{path}',
{#{params.collect { |p| "#{p[0]}: #{p[1]}" }.join(", ")}},
function(data) {$('##{target_tag_id}').html(data);}
);"
end
is there any solution?
as it's not population sub category dropdown.

Why doesn't initialize appear as a method when I call on the instance methods of a class?

I'm writing a blog post on how almost everything is an object in Ruby, and I'm trying to show this through the following example:
class CoolBeans
attr_accessor :beans
def initialize
#bean = []
end
def count_beans
#beans.count
end
end
So from looking at the class we can tell it has 4 methods(unless of course, I'm wrong):
It can initialize a default empty array of beans when a new instance is created
It can count how many beans it has
It can read how many beans it had (through the attr_accessor)
It can write(or add) more beans to the empty array (also through the attr_accessor)
However, when I ask the class itself what instance methods it has, I don't see the default initialize method:
CoolBeans.new.class.instance_methods
# => [:beans, :beans=, :count_beans, :lm, :lim, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
Does this mean that the initialize method is not an instance method? If not, why isn't it showing up as a method available to the class CoolBeans?
instance_methods returns an array of public and protected methods. However, initialize is automatically private ref.
CoolBeans.private_instance_methods
# => [:initialize, :default_src_encoding, :irb_binding, :initialize_copy, :initialize_dup, :initialize_clone, :sprintf, :format, :Integer, :Float, :String, :Array, :Hash, :warn, :raise, :fail, :global_variables, :__method__, :__callee__, :__dir__, :eval, :local_variables, :iterator?, :block_given?, :catch, :throw, :loop, :respond_to_missing?, :trace_var, :untrace_var, :at_exit, :syscall, :open, :printf, :print, :putc, :puts, :gets, :readline, :select, :readlines, :`, :p, :test, :srand, :rand, :trap, :load, :require, :require_relative, :autoload, :autoload?, :proc, :lambda, :binding, :caller, :caller_locations, :exec, :fork, :exit!, :system, :spawn, :sleep, :exit, :abort, :Rational, :Complex, :set_trace_func, :gem, :gem_original_require, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined, :method_missing]
# ^^^^^^^^^^^

Stack level too deep or unknown attribute: password_confirmation

I'm working on a web app that has users model. You either sign up or try the app and be a 'guest'. I had the sign up functionality working well until I added the guest option. I based on Railscast to do this (http://railscasts.com/episodes/393-guest-user-record) and that's when I ran into troubles
Here is my user model code
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_many :bookings
has_one :account, dependent: :destroy
# before_save :downcase_email, allow_nil: true
before_save :create_remember_token
validates_presence_of :name, :email, :password, :password_confirmation, unless: :guest?
validates_uniqueness_of :email, case_sensitive: false , allow_blank: true
validates :name, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, format: { with: VALID_EMAIL_REGEX }, unless: :guest?
validates :password, length: { minimum: 6 }, unless: :guest?
def downcase_email
{ |user| user.email = email.downcase }
end
# has_secure_password
# override has_secure_password to customize validation until Rails 4.
require 'bcrypt'
attr_reader :password, :password_confirmation
include ActiveModel::SecurePassword::InstanceMethodsOnActivation
##def to_param
## "#{id}.#{name.parameterize}"
##end
def self.new_guest
new { |u| u.guest = true }
end
def name
guest ? "Guest" : name
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
and here is my User Controller code:
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:edit, :update]
before_filter :correct_user, only: [:edit, :update]
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = params[:user] ? User.new(params[:user]) : User.new_guest
if #user.save
sign_in #user
#user.create_account.accountPlan = "Free"
##flash[:success] = "Welcome to the HighTide!"
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
#flash[:success] = "Profile updated"
sign_in #user
redirect_to #user
else
render 'edit'
end
end
private
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
you may notice some code is commented out. I wasn't able to store in the database a user without an email (and for have a quick and dirty thing working now I comment the callback before_save, I also might add that I use the guidelines of Michael Hartl tut)
What happens is, when I run this code I get a unknown attribute: password_confirmation error, but when I comment out
require 'bcrypt'
attr_reader :password, :password_confirmation
include ActiveModel::SecurePassword::InstanceMethodsOnActivation
and use has_secure_password instead
I get a stack level too deep
I haven't figured out what to do

Hartls Chapter 11: undefined method `following_user_path'

I am trying to get through the last and final chapter of the Hartl tutorial, but keep getting the below error for multiple tests across all specs. The tests started to fail as soon as I entered in the following/followers behavior into my code. Can anyone see where I'm going wrong?
ActionView::Template::Error:
undefined method `following_user_path'
Here's an example of a spec that is failing:
describe "visiting the following page" do
before { visit following_user_path(user) }
it { should have_in_title('Sign in') }
end
Here's the extracted source from _stats.html.erb (line #3):
<% #user ||= current_user %>
<div class="stats">
<a href="<%= following_user_path(#user) %>">
<strong id="following" class="stat">
<%= #user.followed_users.count %>
</strong>
following
</a>
<a href="<%= followers_user_path(#user) %>">
<strong id="followers" class="stat">
<%= #user.followers.count %>
</strong>
followers
</a>
</div>
routes.rb
SampleApp::Application.routes.draw do
resources :users do
member do
get :following, :followers
end
end
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
root to: 'static_pages#home'
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
end
users_controller.rb
class UsersController < ApplicationController
before_filter :signed_in_user,
only: [:index, :edit, :update, :destroy, :following, :followers]
before_filter :correct_user, only: [:edit, :update]
before_filter :admin_user, only: :destroy
def show
#user = User.find(params[:id])
#microposts = #user.microposts.paginate(page: params[:page])
end
def new
if signed_in?
redirect_to root_path, notice: "Already signed in."
else
#user = User.new
end
end
def create
if signed_in?
redirect_to root_path, notice: "Already signed in."
else
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
render 'new'
end
end
end
def edit
end
def update
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in #user
redirect_to #user
else
render 'edit'
end
end
def index
#users = User.paginate(page: params[:page])
end
def destroy
user = User.find(params[:id])
if (current_user == user) && current_user.admin?
flash[:error] = "Cannot delete own admin account."
else
user.destroy
flash[:success] = "User destroyed."
end
redirect_to users_url
end
def following
#title = "Following"
#user = User.find(params[:id])
#users = #user.followed_users.paginate(page: params[:page])
render 'show_follow'
end
def followers
#title = "Followers"
#user = User.find(params[:id])
#users = #user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
user.rb
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
has_many :microposts, dependent: :destroy
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
validates :password_confirmation, presence: true
def feed
microposts
#Micropost.where("user_id = ?", id)
end
def following?(other_user)
relationships.find_by_followed_id(other_user.id)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by_followed_id(other_user.id).destroy
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
rake routes
following_user GET /users/:id/following(.:format) users#following
followers_user GET /users/:id/followers(.:format) users#followers
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
sessions POST /sessions(.:format) sessions#create
new_session GET /sessions/new(.:format) sessions#new
session DELETE /sessions/:id(.:format) sessions#destroy
microposts POST /microposts(.:format) microposts#create
micropost DELETE /microposts/:id(.:format) microposts#destroy
relationships POST /relationships(.:format) relationships#create
relationship DELETE /relationships/:id(.:format) relationships#destroy
root / static_pages#home
signup /signup(.:format) users#new
signin /signin(.:format) sessions#new
signout DELETE /signout(.:format) sessions#destroy
help /help(.:format) static_pages#help
about /about(.:format) static_pages#about
contact /contact(.:format) static_pages#contact
spec_helper.rb
require 'rubygems'
require 'spork'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
end
end
Spork.each_run do
end
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.include Rails.application.routes.url_helpers
end
Also, this is my first time posting here, so excuse me if I'm not posting things correctly. And please let me know if there's any other useful information I should include. Thanks!
Unfortunately one cannot just call route methods in tests. You can add it though. Check to see if you have this code below in your spec_helper.rb file.
Rspec.configure do |config|
# The line below should be in the file, if not add it.
config.include Rails.application.routes.url_helpers
end
EDIT: Your spec_helper.rb file should look like this
require 'rubygems'
require 'spork'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.include Rails.application.routes.url_helpers
end
end
Spork.each_run do
end
EDIT AGAIN: Spork is a nifty little tool used for running tests. Long story short if you have a lot of tests, it takes awhile. Spork helps ease that by making the tests quicker. Once you get more familiar with testing I suggest you take a look at it.

Paperclip "Gem" Rails 3.1 undefined method model file name

Using rails 3.1.1, Ruby 1.9.2,
Gems: gem 'haml', gem 'simple_form', gem 'aws-sdk',
gem 'paperclip', :git => "git://github.com/thoughtbot/paperclip.git"
plugin: country_select: git://github.com/rails/country_select.git
Having an issue uploading/displaying images pushed to Amazon S3 through paperclip (GEM)
Error: undefined method `avatar_file_name' for #Player:0x00000102aff228
For the most part I was following the example on the git-hub page for paperclip
https://github.com/thoughtbot/paperclip
Here is what I have in my code:
Migration: 20111224044508_create_players.rb
class CreatePlayers < ActiveRecord::Migration
def change
create_table :players do |t|
t.string :first_name
t.boolean :first_name_public, :default => false
...
t.string :website
t.boolean :website_public, :default => false
t.has_attached_file :avatar
t.timestamps
end
end
end
Model: Player.rb:
class Player < ActiveRecord::Base
attr_accessible :first_name, ... :website
validates_presence_of :username, :email
has_attached_file :avatar,
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => ":class/:id/:style/:filename"
{Unrelated validations}
end
S3 file: s3.yml
development:
bucket: voh_development
access_key_id: *********************
secret_access_key: ********************
staging:
bucket: voh_staging
access_key_id: *********************
secret_access_key: ********************
production:
bucket: voh_production
access_key_id: *********************
secret_access_key: ********************
Controller: players_controller.rb
class PlayersController < ApplicationController
def create
#player = Player.create(params[:player])
if #player.save
redirect_to players_path, :notice => "Player Created";
else
render :action => 'new'
end
end
{basic restful}
end
Views:
Edit.html.haml + New.html.haml
= simple_form_for #player do |f|
= f.input :first_name
...
= f.input :website
= f..file_field :avatar
.input_div
= f.button :submit
index.html.haml
...
%td Avatar
%td First Name
...
%td Actions
- #players.each do |player|
%tr
%td
= image_tag #player.avatar.url(:thumb)
%td
= player.first_name
...
%td
= link_to ' Show ', player_path(player.id)
|
= link_to ' Edit ', edit_player_path(player.id)
show.html.haml
= image_tag #user.avatar.url
%br
= #player.first_name
...
Research:
I found a lot to do with the pluging and genration of the migration but it all seems old. Most of them suggest putting in the up down in the migration for the 4 attributes. However it seems that should have been replaced by the one line t.has_attached_file :avatar.
I have a rails 3.0 project and this worked. I am able to upload products and pull them back down. (had to play with the suggested image_tag #icon.avatar.url and turned it into %img{:src => URI.unescape(icon.icon.url)} but that a different question.)
TLDR: Fixed typo in index.html.haml from #player => player, Added :avatar to attr_accessible.
I woke up this morning and had a different error.
instead of: undefined method Avatar_file_name'
I got: undefined method avatar' for nil:NilClass
That error was caused buy a simple type in my code. I used an instance vairable instead of .each variable I should have been using (index.html.haml:9)
Now the app was not erring out but the file was still not uploading.
In the development log I found this. (I did not look here the first time I posted)
WARNING: Can't mass-assign protected attributes: avatar
I then went and added :Avatar to attr_accessible and everything started working.
Not sure if this is supposed to be required or not but I did see that they had updated S3 header to be a proc yesterday.
https://github.com/thoughtbot/paperclip/tree/master/test/storage
I am not going to close this out yet. There will be an edit because I am going to play with the version and quickly report my findings today. Then I will close this out.
Edit:
I tryed switch back to 2.4.5 and I am getting the error that made me switch to pulling master in the first place. When attempting to do a migration with t.has_attached_file :avatar it fails to migrate and gives the following error.
undefined method `has_attached_file' for #ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition:0x00000105053600
I think I will stick with pulling from master.

Resources