How to pass the parameter to pundit policy - ruby-on-rails-6

I am using pundit right now.
But then in my controller, there is a search params with if condition, so I cannot simply use policy_scope to pass the pundit.
Posts_controller
def index
search = params['search']
if search.present?
#content = params['search']
#posts = Post.joins(:user).where("users.content ILIKE ?", "%#{#content}%")
else
#posts = Post.all
end
end
Pundit
def resolve
scope.all
end
I have try like #posts = PostPolicy::Scope.new(current_user, Post, #content).resolve , but it does not work.

Oh actually can do policy_scope(Post).joins(:user).where("users.content ILIKE ?", "%#{#content}%").

Related

How can I start a brand new request in Scrapy crawler?

I am scraping from a website that will give every request session a sid, after getting the sid, I perform further search query with this sid and scrape the results.
I want to change the sid every time I've finished scraping all results of a single query, I've tried clearing the cookies but it doesn't work.
However, if I restart my crawler, it wll get a different sid each time, I just don't know how to get a new sid without restart the crawler.
I am wondering if there're something else that let the server know two requests are from the same connection.
Thanks!
Here is my current code:
class MySpider(scrapy.Spider):
name = 'my_spider'
allowed_domains = ['xxx.com']
start_urls = ['http://xxx/']
sid_pattern = r'SID=(\w+)&'
SID = None
query_list = ['aaa', 'bbb', 'ccc']
i = 0
def parse(self, response):
if self.i >= len(self.query_list):
return
pattern = re.compile(self.sid_pattern)
result = re.search(pattern, response.url)
if result is not None:
self.SID = result.group(1)
else:
exit(-1)
search_url = 'http://xxxx/AdvancedSearch.do'
query = self.query_list[i]
self.i += 1
query_form = {
'aaa':'bbb'
}
yield FormRequest(adv_search_url, method='POST', formdata=query_form, dont_filter=True,
callback=self.parse_result_entry)
yield Request(self.start_urls[0], cookies={}, callback=self.parse,dont_filter=True)
def parse_result(self, response):
do something
Setting COOKIES_ENABLED = False can achieve this, but is there another way other than a global settings?

Drupal Views:Add condition in where clause where the value is a field in hook_alter_query

I am trying to add a condition to a query like:
civicrm_contact_civicrm_relationship.id <> civicrm_contact_civicrm_relationship_1.id
but for the second field drupal takes it as a string so it always result into
civicrm_contact_civicrm_relationship.id <> 'civicrm_contact_civicrm_relationship_1.id'
I've tried to play with the numerical value with no success.
Any idea how can I do this? May be with another hook? any tip will be welcome!
My code:
$view->query->where[2]["conditions"][0]["field"] = "civicrm_contact_civicrm_relationship_1.id";
$view->query->where[2]["conditions"][0]["operator"] = "IS NULL";
$view->query->where[2]["conditions"][0]["value"] = "";
$view->query->where[2]["conditions"][1]["field"] = "civicrm_contact_civicrm_relationship.id";
$view->query->where[2]["conditions"][1]["operator"] = "IS NULL";
$view->query->where[2]["conditions"][1]["value"] = "";
$view->query->where[2]["conditions"][2]["field"] = "civicrm_contact_civicrm_relationship.id";
$view->query->where[2]["conditions"][2]["value"] ="civicrm_contact_civicrm_relationship_1.id";
$view->query->where[2]["conditions"][2]["numeric"] = "1";
$view->query->where[2]["conditions"][2]["operator"] = "<>";
$view->query->where[2]["type"] = "OR";
try something like
function my_hook_views_query_alter(&$view, &$query)
{
if ($view->name == 'my_hook') {
$alias = $query->add_table('civicrm_contact_civicrm_relationship','civicrm_contact_civicrm_relationship_1');
$query->add_where_expression(0,'civicrm_contact_civicrm_relationship.id <> civicrm_contact_civicrm_relationship_1.id');
dpm($query); //dumps object to admin with devel module
}
}

Get HTTP response body as string (BubbleWrap for RubyMotion)

Using RubyMotion (for the first time!), I want to use Twitter's search API to retrieve some recent tweets for some users so have put together the class below.
The value of tweets is always an empty array. I suspect that BW::HTTP.get(url) spawns its own thread which is causing the issue.
Really, I just want twitter_search_results to return response.body.to_str but I am not sure how to do this.
How do I use RubyMotion (or BubbleWrap) to put an array of Tweet objects into my UIViewController?
class TweetsController
def initialize
#twitter_accounts = %w(dhh google)
#tweets = []
end
def tweets
twitter_search_results
puts #tweets.count
#tweets
end
def create_tweets(response)
BW::JSON.parse(response)["results"].each do |result|
#tweets << Tweet.new(result)
end
end
def twitter_search_results
query = #twitter_accounts.map{ |account| "from:#{account}" }.join(" OR ")
url = "http://search.twitter.com/search.json?q=#{query}"
BW::HTTP.get(url) do |response|
create_tweets(response.body.to_str)
end
end
end
class TwitterViewController < UIViewController
def viewDidLoad
super
self.view.backgroundColor = UIColor.blueColor
#table = UITableView.alloc.initWithFrame(self.view.bounds)
self.view.addSubview #table
#table.dataSource = self
#tweets_controller = TweetsController.new
end
def initWithNibName(name, bundle: bundle)
super
self.tabBarItem = UITabBarItem.alloc.initWithTitle(
"Twitter",
image: UIImage.imageNamed('twitter.png'),
tag: 1)
self
end
def tableView(tableView, numberOfRowsInSection: section)
#tweets_controller.tweets.length
end
def tableView(tableView, cellForRowAtIndexPath: indexPath)
#reuse_id = "Tweet"
cell = UITableViewCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier:#reuse_id)
cell.textLabel.text = #tweets_controller.tweets[indexPath.row].text
return cell
end
end
class Tweet
attr_reader :created_at, :from_user, :text
def initialize(tweet_result)
#created_at = tweet_result["created_at"]
#from_user = tweet_result["from_user"]
#text = tweet_result["text"]
end
end
Full controller code below. I've also put the project on GitHub
class TweetsController
def initialize
#twitter_accounts = %w(dhh google)
#tweets = []
create_tweets
end
def tweets
#tweets
end
def create_tweets
json_data = twitter_search_results.dataUsingEncoding(NSUTF8StringEncoding)
e = Pointer.new(:object)
dict = NSJSONSerialization.JSONObjectWithData(json_data, options:0, error: e)
dict["results"].each do |result|
p result.class
p result
#tweets << Tweet.new(result)
end
end
def twitter_search_results
query = #twitter_accounts.map{ |account| "from:#{account}" }.join(" OR ")
url_string = "http://search.twitter.com/search.json?q=#{query}"
url_string_escaped = url_string.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
url = NSURL.URLWithString(url_string_escaped)
request = NSURLRequest.requestWithURL(url)
response = nil
error = nil
data = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: error)
raise "BOOM!" unless (data.length > 0 && error.nil?)
json = NSString.alloc.initWithData(data, encoding: NSUTF8StringEncoding)
end
end
the issue here is asynchronicity. you're almost there, I think, but the create_tweets method is not called before puts #tweets. In this case, I would recommend using a notification, because I think they are good ;-)
TweetsReady = 'TweetsReady' # constants are nice
NSNotificationCenter.defaultCenter.postNotificationName(TweetsReady, object:#tweets)
In your controller, register for this notification in `viewWillAppear` and unregister in `viewWillDisappear`
NSNotificationCenter.defaultCenter.addObserver(self, selector: 'tweets_ready:', name: TweetsReady, object:nil) # object:nil means 'register for all events, not just ones associated with 'object'
# ...
NSNotificationCenter.defaultCenter.removeObserver(self, name:TweetsReady, object:nil)
and you tweets_ready method should implement your UI changes.
def tweets_ready(notification)
#table.reloadData
end

Linq To Sql Get data into Label

I have a label to show BookName. I get it from table which name tblBooks. I don't know how to show Book Name into the label.
var query = from b in dc.tblBooks.Where(b=>b.BookID == 'B01') select b;
Can you help me know.
Your query as written will return a collection of books—IQueryable<Book>. If you're sure there will only be one result in this query, you can call SingleOrDefault, which will execute the query immediately and give you the actual book.
var Book = dc.tblBooks.Where(b => b.BookID == 'B01').SingleOrDefault();
if (Book != null)
myLabel.Text = Book.BookName;
Or you can simply say:
var Book = dc.tblBooks.SingleOrDefault(b => b.BookID == 'B01');
Which does the same thing.
If you're 110% sure there will always be a result, and you don't want to check for null, then you can use Single, which will do the same thing, except throw an exception if no results are found, where SingleOrDefault simple returns null.
var Book = dc.tblBooks.Single(b=>b.BookID == 'B01');
myLabel.Text = Book.BookName;
Try:
label.Text = query.FirstOrDefault().BookName;

Trim function not removing spaces in name

bool Res = false;
DataView DV = new DataView(DT);
DV.RowFilter = "Trim(Originator)='"+OrginatorName.Trim()+"'";
if (DV.Count > 0)
{
Res = true;
}
I need to get "Originator" from the database and compare it with the OrginatorName to check duplicate values. I need to remove all the white spaces before checking.
For example, the function must consider "John Van" to be the same as "JohnVan". My above code doesn't work. How can I achieve this?
String.Trim() removes whitespace from the beginning and end only, not in the middle. You want to use the String.Replace() method
DV.RowFilter = "Trim(Originator)='"+OrginatorName.Replace(" ", "")+"'";
this line should be
DV.RowFilter = "Trim(Originator)='"+OrginatorName.Replace(" ","")+"'";
User .Replace instead of .Trim()

Resources