Not displaying star rating on production (heroku) - ruby-on-rails

I'm using the gem ratyrate, and locally it works fine, but in production it generates a 404 error of the images.
Some solutions I found were these, but they do not work
/initializer/raty_helper.rb
https://github.com/wazery/ratyrate/blob/master/lib/ratyrate/helpers.rb
raty.js.rb
$.fn.raty.defaults.half = false;
$.fn.raty.defaults.halfShow = true;
$.fn.raty.defaults.path = '<%= asset_path('images') %>';
$.fn.raty.defaults.cancel = false;
$(function(){
$(".star").each(function() {
var $readonly = ($(this).attr('data-readonly') == 'true');
var $half = ($(this).attr('data-enable-half') == 'true');
var $halfShow = ($(this).attr('data-half-show') == 'true');
var $single = ($(this).attr('data-single') == 'true');
$(this).raty({
score: function() {
return $(this).attr('data-rating')
},
number: function() {
return $(this).attr('data-star-count')
},
half: $half,
halfShow: $halfShow,
single: $single,
path: $(this).attr('data-star-path'),
starOn: '/star-on.png',
starOff: '/star-off.png',
starHalf: '/star-half.png',
cancel: $(this).attr('data-cancel'),
cancelPlace: $(this).attr('data-cancel-place'),
cancelHint: $(this).attr('data-cancel-hint'),
cancelOn: '/cancel-on.png',
cancelOff: '/cancel-off',
noRatedMsg: $(this).attr('data-no-rated-message'),
round: $(this).attr('data-round'),
space: $(this).attr('data-space'),
target: $(this).attr('data-target'),
targetText: $(this).attr('data-target-text'),
targetType: $(this).attr('data-target-type'),
targetFormat: $(this).attr('data-target-format'),
targetScoret: $(this).attr('data-target-score'),
readOnly: $readonly,
click: function(score, evt) {
var _this = this;
if (score == null) { score = 0; }
$.post('<%= Rails.application.class.routes.url_helpers.rate_path %>',
{
score: score,
dimension: $(this).attr('data-dimension'),
id: $(this).attr('data-id'),
klass: $(this).attr('data-classname')
},
function(data) {
if(data) {
// success code goes here ...
if ($(_this).attr('data-disable-after-rate') == 'true') {
$(_this).raty('set', { readOnly: true, score: score });
}
}
});
}
});
});
});

Add to your your config/environments/production.rb:
config.serve_static_assets = true

The solution is to execute this command:
rails assets:precompile

Related

Camera doesn't work after compilation

I use Ionic Framework.
Camera works perfectly in Ionic View. But it doesn't work after compilitaion on iOS.
Please, help to find out what is the problem.
Camera code in services.js:
app.factory('FileService', function() {
var images;
var IMAGE_STORAGE_KEY = 'dav-images';
function getImages() {
var img = window.localStorage.getItem(IMAGE_STORAGE_KEY);
if (img) {
images = JSON.parse(img);
} else {
images = [];
}
return images;
};
function addImage(img) {
images.push(img);
window.localStorage.setItem(IMAGE_STORAGE_KEY, JSON.stringify(images));
};
return {
storeImage: addImage,
images: getImages
}
});
app.factory('ImageService', function($cordovaCamera, FileService, $q, $cordovaFile) {
function optionsForType(type) {
var source;
switch (type) {
case 0:
source = Camera.PictureSourceType.CAMERA;
break;
case 1:
source = Camera.PictureSourceType.PHOTOLIBRARY;
break;
}
return {
quality: 90,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: source,
allowEdit: false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
};
}
function saveMedia(type) {
return $q(function(resolve, reject) {
var options = optionsForType(type);
$cordovaCamera.getPicture(options).then(function(imageBase64) {
FileService.storeImage(imageBase64);
});
})
}
return {
handleMediaDialog: saveMedia
}
});
Camera code in controllers.js:
app.controller('CameraController', function($scope, $cordovaDevice, $cordovaFile, $ionicPlatform, $cordovaEmailComposer, $ionicActionSheet, ImageService, FileService) {
$ionicPlatform.ready(function() {
$scope.images = FileService.images();
$scope.$apply();
});
$scope.addMedia = function() {
$scope.hideSheet = $ionicActionSheet.show({
buttons: [
{ text: 'Take photo' },
{ text: 'Photo from library' }
],
titleText: 'Add images',
cancelText: 'Cancel',
buttonClicked: function(index) {
$scope.addImage(index);
}
});
}
$scope.addImage = function(type) {
$scope.hideSheet();
ImageService.handleMediaDialog(type).then(function() {
$scope.$apply();
});
}
$scope.sendEmail = function() {
if ($scope.images != null && $scope.images.length > 0) {
var mailImages = [];
var savedImages = $scope.images;
for (var i = 0; i < savedImages.length; i++) {
mailImages.push('base64:attachment'+i+'.jpg//' + savedImages[i]);
}
$scope.openMailComposer(mailImages);
}
}
$scope.openMailComposer = function(attachments) {
var bodyText = '<html><h2>My Images</h2></html>';
var email = {
to: '',
attachments: attachments,
subject: 'Devdactic Images',
body: bodyText,
isHtml: true
};
$cordovaEmailComposer.open(email, function(){
console.log('email view dismissed');
}, this);
}
});
To resolve this problem you need to compile an app with XCode.
After XCode compilation camera works correctly.
Probably, the problem with camera was caused by Ionic compilation.

Kendo UI Treelist rows disappears after editing

I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}

Worker path is not fired error says 404 (Not Found)

Reference doc:- https://github.com/ajaxorg/ace/wiki/Syntax-validation
I added createWorker method to the custom mode according to the above doc, and included the worker-example.js in the same file and called require("ace/config").set("workerPath", "ace/mode") in mode definition
Currently, the workerPath is not being fired, I'm seeing a "GET http://localhost:3000/ace/mode/worker-example.js 404 (Not Found)" error in the console.
Here is my custom code index.html.erb :
define('ace/mode/example-custom', [], function(require, exports, module) {
var oop = require("ace/lib/oop");
var TextMode = require("ace/mode/text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
var ExampleHighlightRules = require("ace/mode/example_highlight_rules").ExampleHighlightRules;
var WorkerClient = require("ace/worker/worker_client").WorkerClient;
require("ace/config").set("workerPath", "ace/mode");
var Mode = function() {
this.HighlightRules = ExampleHighlightRules;
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "--";
this.blockComment = {start: "->", end: "<-"};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], workerpath, "WorkerExample");
worker.attachToDocument(session.getDocument());
console.log("worker", worker);
worker.on("errors", function(e) {
session.setAnnotations(e.data);
});
worker.on("annotate", function(results) {
session.setAnnotations(results.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
define('ace/mode/worker-example', [], function(require, exports, module) {
var oop = require("ace/lib/oop");
var Mirror = require("ace/worker/mirror").Mirror;
var WorkerExample = exports.WorkerExample = function(sender) {
Mirror.call(this, sender);
this.setTimeout(200);
};
oop.inherits(WorkerExample, Mirror);
(function() {
this.onUpdate = function() {
var lines = editor.session.doc.getAllLines();
var errors = [];
for (var i = 0; i < lines.length; i++){
if (/[\w\d{(['"]/.test(lines[i])) {
alert("hello");
errors.push({
row: i,
column: lines[i].length,
text: "Missing Semicolon",
type: "error"
});
}
}
this.sender.emit("annotate", errors);
};
}).call(WorkerExample.prototype);
});

OncellChange Event of Slickgrid

I have a slickgrid with a checkbox column.
I want to capture the row id when the checkbox in the selected row is checked or unchecked.
Attached is the script for slickgrid in my view
I want when user checks the checkbox, active column in database should be set to true and when it is unchecked, Active column should be set to false.
<script type="text/javascript">
//$('input[type="button"]').enabled(false);
var grid;
var columnFilters = {};
var jsonmodel = #Html.Raw(Json.Encode(Model));
//function LoadNewMessagesData(messages) {
var dataView;
var data = [];
////console.log('lena:' + subdata.length);
$.each(jsonmodel, function (idx, spotlight) {
var pd = moment(spotlight.PostedDate);
data.push({ id: spotlight.ID, Department: spotlight.SubSection,Title: spotlight.Title, PostedDate: pd.format('YYYY-MM-DD'), Active: spotlight.Active })
});
var columns = [
{ id: '0', name: "Department", field: "Department", sortable: true},
{ id: '1', name: "Title", field: "Title", sortable: true},
{ id: '2', name: "PostedDate", field: "PostedDate", sortable: true }
];
var checkboxSelector = new Slick.CheckboxSelectColumn({
cssClass: "slick-cell-checkboxsel"
})
columns.push(checkboxSelector.getColumnDefinition());
var options = {
enableCellNavigation: true,
explicitInitialization: true,
enableColumnReorder: false,
multiColumnSort: true,
autoHeight: true,
forceFitColumns: true
};
dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel());
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
grid.registerPlugin(checkboxSelector);
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
console.log('testing');
grid.render();
});
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({ enableAddRow: enableAddRow });
}
});
var rowIndex;
grid.onCellChange.subscribe(function (e, args) {
console.log('onCellChange');
rowIndex = args.row;
});
if (grid.getActiveCell()) {
}
//onSelectedRowsChanged event, if row number was changed call some function.
grid.onSelectedRowsChanged.subscribe(function (e, args) {
if (grid.getSelectedRows([0])[0] !== rowIndex) {
console.log('onSelectedRowsChanged');
}
});
grid.onSort.subscribe(function (e, args) {
var cols = args.sortCols;
var comparer = function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
}
dataView.sort(comparer, args.sortAsc);
});
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
// dataView.setFilter(filter);
dataView.endUpdate();
//}
function RefreshMessagesGrid() {
//console.log('RefreshMessagesGrid');
//grid.invalidate();
grid.invalidateRows();
// Call render to render them again
grid.render();
grid.resizeCanvas();
}
</script>`enter code here`
Thanks in Advance !!!
You have to bind click event on rows....and get the id of the row whose checkbox is checked/unchecked
function bindClickOnRow() {
if($(this).find('.checkboxClass').attr('checked') == 'checked'){
checked = true;
} else {
checked = false;
}
rowId = $(this).attr('id');
}

Keep impromptu "up" while performing a jquery Ajax/MVC post

Is there a way to keep the impromptu dialog box displayed during a post?
Here's the javascript code
$('#linkPostTest').click(function() {
openprompt();
});
function openprompt() {
var temp = {
state0: {
html: 'Are you sure you want to post?<br />',
buttons: { Yes: true, No: false },
focus: 1,
submit: function(v, m, f) {
if (v) {
var form = $('frmPostTest');
$.ajax(
{
type: 'POST',
url: '/Path/TestPost',
data: form.serialize(),
success: function(data) {
// I realize I could check "data"
// for true...just have not
// implemented that yet....
$.prompt.goToState('state1');
//$.prompt('Test was successful!');
},
error: function() {
$.prompt.goToState('state2');
//$.prompt('Test was not successful.');
}
}
);
return true;
}
else {
//$.prompt.goToState('state1'); //go forward
return false;
}
}
},
state1: {
html: 'Test was successful!',
buttons: { Close: 0 },
focus: 0,
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
},
state2: {
html: 'Test was not successful.<br />',
buttons: { Close: 0 },
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
}
};
$.prompt(temp);
}
The controller does this
[AcceptVerbs(HttpVerbs.Post)]
public bool TestPost()
{
// runs some code that saves some data...
// this works fine
bool updated = functionThatSavesCode();
return updated;
}
After I click Yes when the 'Are you sure you want to post?' impromptu dialog is displayed... it disappears...How can I make it stay displayed?
OK got it to work...I'm really impressed with the impromptu plug-in and jQuery!
Two of the things I did differently to get this to work was to add the two
return false;
statements under the state0 block and...
to set the the ajax call to
async: false,
Here's the new javascript:
$('#linkTestPost').click(function() {
TestPost();
});
function TestPost() {
var temp = {
state0: {
html: 'Are you sure you want to post?<br />',
buttons: { Yes: true, No: false },
focus: 1,
submit: function(v, m, f) {
if (v) {
if (PostView() === true) {
$.prompt.goToState('state1');
// the line below was missing from my original attempt
return false;
}
else {
$.prompt.goToState('state2');
// the line below was missing from my original attempt
return false;
}
}
else {
return false;
}
}
},
state1: {
html: 'Test Post was successful!',
buttons: { Close: 0 },
focus: 0,
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
},
state2: {
html: 'Test Post was not successful',
buttons: { Close: 0 },
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
}
};
$.prompt(temp);
}
function PostView() {
var form = $('frmTestPost');
var postSuccess = new Boolean();
$.ajax(
{
type: 'POST',
url: '/Path/TestPost',
data: form.serialize(),
// the line below was missing from my original attempt
async: false,
success: function(data) {
postSuccess = true;
},
error: function() {
postSuccess = false;
}
});
return postSuccess;
}

Resources