uninitialized constant ActionView::CompiledTemplates::FB Ruby on Rails - ruby-on-rails

I am using ruby 1.9.3 Rails 3.2.13 for making an app that can post on facebook wall by using a dialog box (feed dialog)
In my view -
<%
FB.ui(
{
method: 'feed',
name: 'The Facebook SDK for Javascript',
caption: 'Bringing Facebook to the desktop and mobile web',
description: (
'A small JavaScript library that allows you to harness ' +
'the power of Facebook, bringing the user\'s identity, ' +
'social graph and distribution power to your site.'
),
link: 'https://developers.facebook.com/docs/reference/javascript/',
picture: 'http://www.fbrell.com/public/f8.jpg'
},
function(response) {
if (response && response.post_id)
alert('Post was published.')
else
alert('Post was not published.')
end
}
);
%>
IN MY controller
def func
cache_expire = 1.year
response.headers["Pragma"] = "public"
response.headers["Cache-Control"] = "max-age=#{cache_expire.to_i}"
response.headers["Expires"] = (Time.now + cache_expire).strftime("%d %m %Y %H:%I:%S %Z")
render :layout => false, :inline => "<script src='//connect.facebook.net/en_US/all.js'></script>"
redirect_to root_path
end
It is given this error on my view page -
uninitialized constant ActionView::CompiledTemplates::FB
on FB.ui line..
please help I am new with this!

It looks like you're trying to mix Ruby and JavaScript in your view, but you only need JavaScript. Try removing the erb tags <% from your view and wrapping the JS in <script> tags.

Related

API Requests not being sent in Production w/Excon Rails 6.0.0

I'm having an issue where my POST request with Excon gem is not being sent out in production, but works perfectly in development. In my logs, it shows Processing ServiceFormsControlller#run_background_check as HTML. I don't know exactly why this is happening...It was working perfectly last week. Now all of a sudden, no requests are being sent out from the production server...It shows the action taking place, but the API endpoint never receives the POST. I added the website to my CORS configuration as a whitelisted domain. That didn't do anything to improve the results.
service_forms_controller.rb
class ServiceFormsController < ApplicationController
#service_form = ServiceForm.find(params[:id])
#service_info = #service_form.info
if #service_info.first_name.present? && #service_info.last_name.present? && #service_info.ssn.present? && #service_info.address.present? && #service_info.email.present?
#report_builder = GoodHire.new
if Rails.env.production?
#report_builder.create_report_for_candidate(#service_info.first_name, #service_info.last_name, #service_info.ssn, #service_info.address, #service_info.email)
# other mandatory fields added to this call
end
redirect_to service_forms_path, notice: "You've submitted the candidate for a background check"
else
redirect_to service_forms_path, notice: "The candidate doesn't have all fields completed"
end
good_hire.rb
class GoodHire
API_KEY_PROD = 'ZZzazzee'
include RestClient
include Excon
def create_report_for_candidate(first_name, last_name, email, ssn, address, city, state, zip, work_histories =[].....,api_key = API_KEY_PROD)
begin
Excon.post("https://api.goodhire.com/v1/Report", body: {
"Candidate": {
"FirstName": "#{first_name}"
....
...
},
"Offer": {
"Products": [
"....ID"
]
},
"RequestOptions": {
"SendPurchaseReceipt": true
}
}.to_json, headers: {"Content-Type" => "application/json", "Authorization" => "ApiKey #{api_key}"})
rescue Excon::Errors => e
puts "RESPONSE ERROR #{e.response}"
end
end
Server Development Log
Started POST "/service_forms/7/run_candidate_bckground_check?id=7" for 127.0.0.1
Processing by ServiceFormsController#run_candidate_background_check as HTML
Parameters: {"authenticity_token" => "zregegegergergergegegege", "id" => "7", "service_form_id"=> "7"}
app/controllers/service_forms_controller.rb: in `run_candidate_background_check'
Redirected to https://127.0.0.1:3000/service_forms
Completed 302 Found in 4359ms
Started GET "/service_forms" for 127.0.0.1
initate_background_check.html.erb
<body>
<%= button_to service_form_run_candidate_background_check(service_form_id: #service_form.id, id: #service_form.id), method: :post, class: 'bttn-simple bttn-sm bttn-primary'do %>
Start Background Check
<% end %>
</body>
API Validations caused API requests to fail

Rails 5.2 TinyMCE Image Uploads with Amazon S3

I'm using this tutorial to try to facilitate image uploads using the TinyMCE WYSIWYG editor on my rails 5.2 app.
So far I have implemented all the code in the tutorial and everything works perfectly, but when I try to upload an image I get a "Got a bad response from the server" error message.
In my heroku logs I then get this:
FATAL -- : [527c4468-9ebe-475a-97a9-380bfc327aab] ActionController::RoutingError (uninitialized constant #<Class:0x000055b6d991e020>::EditController
2020-02-22T17:34:07.814727+00:00 app[web.1]: Did you mean? DeviseController):
Here is the route I'm using:
post '/tinymce_assets', to: 'article/edit#image_upload'
With these controller methods:
def image_upload
file = params[:file]
url = upload_file(file)
render json: {
image: {
url: url
}
}, content_type: "text/html"
end
private
def upload_file(file)
s3 = Aws::S3::Resource.new(region:ENV['AWS_REGION'])
obj = s3.bucket(ENV['S3_BUCKET_NAME']).object('articles/images/content/' + filename(file))
obj.upload_file(file.tempfile, {acl: 'public-read'})
obj.public_url.to_s
end
def filename(file)
file.original_filename.gsub(/[^a-zA-Z0-9_\.]/, '_')
end
And this to initialize it:
<%= f.text_area :body, class: "tinymce", rows: 20, cols: 120 %>
<%= tinymce :content_css => asset_path('application.css')%>
...
<script>
$(document).ready(function() {
tinymce.init({
selector: "textarea.tinymce", // change this value according to your HTML
});
});
</script>
Can anyone see where I'm going wrong here?
Rails is trying to find an EditController because of your route: post '/tinymce_assets', to: 'article/edit#image_upload'
This route suggests that the controller it should look in is Article::EditController. Since you are actually looking for the ArticlesController you should change your route to be:
post '/tinymce_assets', to: 'articles#image_upload'
The Rails routing documentation can be helpful, specifically section 2.2 and 2.6. https://guides.rubyonrails.org/routing.html

How to have capybara see page change after ajax call to rails?

I am writing a feature spec:
the steps are:
List item
I add a new record
I overwrite its verification_date to be nil
This makes it list with a 'verify' link
I click the verify link
If the url is valid the screen should (via ajax) update the 'verify' link to be '2014' text.
This is current working fine in the actual application, the problem is in trying to add some tests that will replicate the behaviour and reflect a working process.
I can't seem to get the test to recognize changed text from the ajax call.
I can do the steps manually but when I use the spec it doesn't see an updated page.
I make sure (in the spec) that I only have (and have added only) 1 record.
Whatever I do I get
1) verification lets me verify a link
Failure/Error: expect(page).to have_content(this_year)
expected to find text "2014" in "Test Linker Links New Link Gr...
The spec is:
...
describe "verification", :type => :feature do
before :all do
User.create(:username => 'x#google.com', :password => 'xyz')
end
before :each do
visit '/ladmin/login'
fill_in 'username', :with => 'x#google.com'
fill_in 'password', :with => 'xyz'
find('input[value="Login"]').click
end
it "lets me verify a link" do
Link.delete_all
expect(Link.count).to eq 0
this_year=Time.now.strftime('%Y') # This is what the screen gets after verification
visit links_path
expect(page).to_not have_content(this_year) # true
l=FactoryGirl.create(:valid_url_link)
l.save
l.update_column(:verified_date, nil) # Force condition that makes 'verify' appear
expect(Link.count).to eq 1
visit links_path
find('a', text: "verify") # This seems to work. The one record has a 'verify' link
click_link("verify", match: :first) # This should change the text to 2014
sleep(7)
expect(page).to have_content(this_year)
end
end
the link factory is:
FactoryGirl.define do
factory :link do
group {FactoryGirl.create(:group)} #:group
url_address {"http://test.com"+SecureRandom.uuid}
alt_text "examples of common situations amnd solutions"
end
factory :valid_url_link, parent: :link do
group {FactoryGirl.create(:group)} #:group
url_address {"http://www.google.com"}
alt_text "valid url"
end
...
end
The js (though probably not where the issue is imho) is:
$ cat app/assets/javascripts/verifying_link.js
$(function(){
$("a[data-verifying-link]='yes'").click(function(event){
event.preventDefault();
a=$(this).parent();
a.html('<img src="assets/ajax-loader.gif">');
var id= $(this).data("id");
var row = $(this).data("tableRow");
$.ajax({
url: "/verify_link/"+id+"&table_row="+row,
type: 'GET',
success: function(r) {
$("span#verify_link_"+row).html('<span class="done">Verified</span>');
},
error: function(r) {
$("span#verify_link_"+row).html('<span class="undone">Unverified</span>');
}
});
});
});
The code for the actual display of the field is a bit messy (but has worked for 378 links so far...) is:
%td.column_align
%span{id: "verify_link_#{index}"}
- if link.verified_date
- link_text = session[:full_details] == 'true' ? long_form(link.verified_date) : short_form(link.verified_date)
= render :partial => 'link_toggle', :locals => { :content => [long_form(link.verified_date), short_form(link.verified_date)], :url => verify_link_path(id: link.id, table_row: index) }
- else
- if session[:user_id]
%a{href: "#", :data => {verifying_link: 'yes', id: link.id, table_row: index}}
verify
- else
No
The partial involved is:
- if session[:full_details] == 'true'
%span{class: "show_hide shown"}
= link_to content[0], url, title: 'Reverify this link', remote: true
%span{class: "show_hide hidden"}
= link_to content[1], url, title: 'Reverify this link', remote: true
- else
%span{class: "show_hide shown"}
= link_to content[1], url, title: 'Reverify this link', remote: true
%span{class: "show_hide hidden"}
= link_to content[0], url, title: 'Reverify this link', remote: true
That needs work but has been working that way for a while in the live app.
Why does the test keeps showing the page with the links added but not verified and showing 2014?
The spec shown does not have the required :js => true
e.g.
describe "verification", :js => true, :type => :feature do
This will then require you (via an error) to add capybara-webkit to your Gemfie, e.g.
gem 'selenium-webdriver'# For rspec capybara javascript tests
and of course
bundle

Capybara::ElementNotFound - How to click on specific button with id using Capybara

Trying to access this button on root url:
here is html
with this test:
feature "New comment button" do
scenario "User can add new comment on root page", :js => true do
visit root_path
id = 152
click_button("#button_#{id}")
within("#comment_row_#{id}") do
fill_in('content', :with => 'this is a comment')
click_button('create comment')
page.must_have_flash_message('Successfully created')
end
end
and geting this:
Capybara::ElementNotFound: Unable to find button "#button_152"
How to get this element using id ?
I am using selenium-web-driver
EDIT
WHAT I TRIED
# page.driver.browser.switch_to.frame 'top-frame' # Selenium::WebDriver::Error::NoSuchFrameError: Unable to locate frame: top-frame
# page.find('#button_152').click # not working
# click_button("#button_152") # not working
# first(:xpath, '//button[#id="button_152"]').click
2.This is an overview of frames :
all iframes are just google chrome addons
4.link to full html
You can read about switching windows and frames here: http://docs.seleniumhq.org/docs/03_webdriver.jsp#moving-between-windows-and-frames
Ruby specific bindings here: https://code.google.com/p/selenium/wiki/RubyBindings
Capybara handling iframes: handling iframe with capybara ruby
As for your problem, here's an example you can edit:
within_frame 'evernoteFilingTools' do
click_button("#button_#{id}")
#button_#{id} # not working
#page.find("#button_#{id}",:visible => true).click # does not work as well
within("#comment_row_#{id}") do
fill_in('content', :with => 'this is a comment')
click_button('create comment')
page.must_have_flash_message('Successfully created')
end
end
You should replace evernoteFilingTools with the iframe ID that contains the content you want to manipulate
Sometimes, it can be thrown off by invalid markup. This HTML has a div (<div class="icons">) inside a table, which is not valid. Try running the markup through a validator such as http://validator.w3.org/ and fix any errors it reports. That might fix your Capybara problem as well.

Integrate Jasper in Rails 3

I'm trying to integrate a rails 3 app with jasper following this wiki:
http://wiki.rubyonrails.org/rails/pages/HowtoIntegrateJasperReports
But it seems that a lot of information isn't updated so it's been very hard to make it work by myself. I've also read a topic at ruby-forum: http://www.ruby-forum.com/topic/139453
with some details explained but still couldn't make it work.
My first problem is related with the render_to_string method:
When the controller method runs I receive a "Template is missing" error:
this is the method:
def report
#customers = Customer.all
send_doc(render_to_string(:template => report_customers_path, :layout => false), '/pdfs', 'report.jasper', "customers", 'pdf')
end
Although this seems simple I'm not understanding why is this happening. Doesn't render_to_string with layout => false suposed to get me the string result of that action?
I also tried :action instead of :template, but it does the same.
If anybody with some expertise with this integration could help...
Thanks in advance,
André
We actually use jasperreports to create reports, and recently upgraded to Rails 3.0. To create the xml, we use xml.erb templates. Jasper reports runs in a separate glassfish server Here's the general idea:
url = URI.parse(my_url_string)
dataxml = render_to_string(:template => my_template_name).gsub(/\n/, '')
params = {'type' => 'pdf', 'compiledTemplateURI' => my_jasper_file, 'data' => dataxml }
request = Net::HTTP::POST.new(url.request_uri)
request.set_form_data(params)
obj = Net::HTTP.new(url.host, url.port)
obj.read_timeout = my_timeout_setting
response = obj.start { |http| http.request(request) }
case response
when Net::HTTPOK
send_data(response.body, :filename => my_chosen_filename, :type => "application/pdf", :disposition => "inline")
else
raise "failed to generate report"
end
I don't know anything about jasper, but it sounds like you want to do two things: render a PDF template and then send the raw output back w/ a PDF mime type:
pdf_contents = render_to_string(:template => 'users/report')
send_data(pdf_contents, :file_name => 'report.pdf', :type => 'application/pdf')
You're passing in the external URL as the template path, but that's probably wrong if you're getting errors about the template path. Fix the template path first.
Use savon to interact with jaserserver in rails3.
Here is an example:
require 'logger'
require 'savon'
logger = Logger.new(STDOUT)
logger.info "Test jasper via Savon-SOAP"
#client = Savon::Client.new {
wsdl.document = "http://localhost:8080/jasperserver/services/repository?wsdl"
http.auth.basic "jasperadmin", "jasperadmin"
}
logger.info "runReport method"
begin
result = #client.request :run_report do
soap.body = "<requestXmlString>
<![CDATA[
<request operationName='runReport' >
<argument name='RUN_OUTPUT_FORMAT'>PDF</argument>
<resourceDescriptor name='' wsType='' uriString='/reports/samples/AllAccounts' isNew='false'>
<label></label>
</resourceDescriptor>
</request>
]]>
</requestXmlString>"
end
send_data result.http.raw_body, :type => 'application/pdf', :filename => 'report.pdf', :disposition => 'attachment'
rescue Exception => e
logger.error "SOAP Error: #{e}"
end
Try to change the render_to_string() code to this:
#customers.to_xml

Resources